vue中你可能不经常用到的知识

vue 引入公共组件之 require.context

1.场景:如页面需要导入多个组件,原始写法:

import test from '@/components/test'
import test1 from '@/components/test1'
import test2 from '@/components/test2'
components:{test,test1,test2}

知识兔

2.这样就写了大量重复的代码,利用 require.context 可以写成

  在main.js中
  const path = require('path')
  const files = require.context('./components', false, /\.vue$/)
  const modules = {}
  files.keys().forEach(key => {
    const name = path.basename(key, '.vue')
    console.log(name, '组件名称')
    modules[name] = files(key).default || files(key)
    console.log(modules, '值')
    Vue.component(name, files(key).default || files(key))
 })
在所需要的页面直接使用
<template>
  <div>
  <test></test>
  </div>
<template>

2、侦听器的handler方法和immediate属性

侦听器的handler方法和immediate属性

var vm = new Vue({

  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      console.log('第一次没有执行')
      this.fullName = val + '·' + this.lastName
    }
  }
})
知识兔

 初始化的时候

firstName函数并没有执行
知识兔
fullName并没有值
 

如果想firstName在第一次被绑定的时候就执行:

watch: {  firstName: {    handler(val){      console.log('第一次执行了')      this.fullName = val + '·' + this.lastName    },    immediate:true//在watch中声明后立即执行handler  }}

 注意看:

fullName 现在是有值

3.4listeners

2.4.0 新增 这两个是不常用属性,但是高级用法很常见; 1.attrs获取子传父中未在 props 定义的值

// 父组件<home title="这是标题" width="80" height="80" imgUrl="imgUrl"/>// 子组件mounted() {  console.log(this.$attrs) //{title: "这是标题", width: "80", height: "80", imgUrl: "imgUrl"}},复制代码

相对应的如果子组件定义了 props,打印的值就是剔除定义的属性

props: {  width: {    type: String,    default: ''  }},mounted() {  console.log(this.$attrs) //{title: "这是标题", height: "80", imgUrl: "imgUrl"}},复制代码

2.listeners" 传入内部组件——在创建更高层次的组件时非常有用

// 父组件<home @change="change"/>// 子组件mounted() {  console.log(this.$listeners) //即可拿到 change 事件}复制代码

如果是孙组件要访问父组件的属性和调用方法,直接一级一级传下去就可以

3.inheritAttrs

// 父组件<home title="这是标题" width="80" height="80" imgUrl="imgUrl"/>// 子组件mounted() {  console.log(this.$attrs) //{title: "这是标题", width: "80", height: "80", imgUrl: "imgUrl"}},inheritAttrs默认值为 true,也就是父组件上的属性会显示到根组件上如果设置为 false 就会隐藏

作者:火狼1
链接:https://juejin.im/post/5d9d386fe51d45784d3f8637
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 
 
计算机