Vue 进阶属性

133 阅读1分钟

自定义指令(directives)

声明全局指令

Vue.directive('x',directiveOptions)
可以在任意组件使用v-x

Vue.directive('x',{
  inserted: function (el) {
    el.addEventListener('click', ()=>{console.log('hi')})
  },
})
当被绑定的元素插入到页面中时,监听函数,把v-x放到哪个元素上,el就代表哪个元素

声明局部指令

directives:{
  'x':{
    inserted(el){
      el.addEventListener('click', ()=>{console.log('hi')})
    }
  }
},

directiveOptions属性

五个函数的属性
bind(el,info,vnode,oldVnode)          类似created
inserted(el,info,vnode,oldVnode)      类似mounted
update(el,info,vnode,oldVnode)        类似updated
componentUpdated(el,info,vnode,oldVnode)          
unbind(el,info,vnode,oldVnode)        类似destroyed

el    绑定的元素
info  可以拿到用户传了什么,info.value把用户传的东西算好,直接使用value
vnode 元素对应的虚拟节点
oldVnode 之前的虚拟节点

仿写v-on指令

 directives: {
  on2: {
    bind(el, info) {
      el.addEventListener(info.arg, info.value);
    },
    unbind(el, info) {
      el.removeEventListener(info.arg, info.value);
    }
  }
}
Vue 自带的 v-on 并不是这样实现的,它更复杂,用了事件委托
声明on2指令,当元素插入到页面中,监听元素的arg事件,对应的方法是用户传来的值value
unbind 删除监听,当元素要死时,调用这个指令

mixins 混入(复制)

mixin提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能

const log = {
  data() {
    return {
      name: undefined,
      time: undefined
    };
  },
  created() {
    if (!this.name) {
      throw new Error("need name");
    }
    this.time = new Date();
    console.log(`${this.name}出生了`);
  },
  beforeDestroy() {
    const now = new Date();
    console.log(`${this.name}死亡了,共生存了 ${now - this.time} ms`);
  }
};
export default log;

<template>
  <div>Child1</div>
</template>

<script>
import log from "../mixins/log.js";
export default {
  data() {
    return {
      name: "Child1"
    };
  },
  created() {
    console.log("Child 1 的 created");
  },
  mixins: [log]
};
</script>

if(!this.name){
    throw new Error("need name");
}

mixins里设置空的name,使用的地方,会自动检查name,自动合并
所有构造选项中的东西,都能写到mixins里

extends 继承(也是复制,与mixins形式不同)

允许声明扩展另一个组件(可以是一个简单的选项对象或构造函数)
而无需使用 Vue.extend,这主要是为了便于扩展单文件组件

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(注入)

允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深
并在起上下游关系成立的时间里始终生效

provide() {
    return {
      themeName: this.themeName,
      fontSizeNmae: this.fontSizeName,
      changeTheme: this.changeTheme,
      changeFontSize: this.changeFontSize
    };
  },

<script>
export default {
  inject: ["themeName", "changeTheme", "changeFontSize"]
};
</script>

练习代码:换肤

详细资料:Vue.js文档