Vue进阶属性

244 阅读1分钟

Direvtives 指令

一、声明一个全局指令

Vue.directive('x', directiveOptions)
就可以再任意组件用v-x 了 ,例如:

Vue.directive('x', {
    inserted(el){
       el.addEventListener('click', ()=>{
          console.log('x')
       })
    }
})//点击元素就打印 'x'

二、声明一个局部指令

new Vue({ 
  ...,
  directives: { 
     "x": directiveOptions 
} 
})

举例:

directives:{
    'x':{
      inserted(el){
        el.addEventListener('click',()=>{console.log('x')})
      }
    }
  },//点击元素就打印 'x'

directiveOptions

  • 五个函数属性
  • bind(el,info,vnode,oldVnode) -类似created
  • inserted(参数同上)- 类似mounted
  • update(参数同上)- 类似updated
  • componentUpdated(参数同上)用得不多
  • unbind(参数同上)- 类似destroyed

指令的作用

主要用于DOM操作

  • Vue实例、组件用于数据绑定、事件监听、DOM更新
  • Vue指令主要目的就是原生DOM

减少重复

  • 如果某个DOM操作你经常使用,就可以封装为指令
  • 如果某个DOM操作比较复杂,也可以封装为指令

mixins 混入

混入就是复制

可以用于智能合并

  • 全局用Vue.mixin({...})
  • 局部用options.mixins:[mixin1,mixin2]
  • 作用是减少options里的重复 事例

extends

extends是比mixins更抽象一点的封装

  • 全局用Vue.extend({})
  • 局部用options.extends:{...}
  • 与mixins同样的需求可以写成:
  • 作用跟mixins差不多,知识形式不同
const MyVue = Vue.extend({
   data(){ return {name:'',time:undefined} },
   created(){
    if(!this.name){console.error('no name!')}
    this.time = new Date()
},
   beforeDestroy(){
     const duration = (new Date()) - this.time
     console.log(
         `${this.name}存活时间${duration}`)
   }
})

provide/inject提供和注入

  • 祖先提供东西,后代注入东西
  • 作用是大范围、隔N代共享信息 举例