Vue自定义指令

139 阅读1分钟

自定义指令:官网

全局指令: 任何组件都能使用

创建方式: Vue.directive('指令名', directiveOptions)

局部指令: 仅用于当前实例

创建方法: directives:{'指令名': directiveOptions}

directiveOptions: 指令定义对象,可以提供几个钩子函数

常用钩子函数:

  • bind: 只调用一次,指令第一次绑定到元素时调用,类似created
  • inserted: 被绑定元素插入父节点时调用,类似mounted
  • update: 所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前,类似updated
  • componentUpdated: 指令所在组件的 VNode 及其子 VNode 全部更新后调用
  • unbind: 只调用一次,指令与元素解绑时调用,类似destroyed

钩子函数参数:

  • el: 指令绑定的元素,可以直接操作DOM
  • binding: 只读 一个对象,包含以下内容
  • Vnode: 只读
  • oldNode: 只读

举例: 自制简易v-on指令 v-on2

new Vue({
  directives: {
    on2: {
      inserted(el, info) {
        el.addEventListener(info.arg, info.value);
      },
      unbind(el, info) { // 取消监听
        el.removeEventListener(info.arg, info.value);
      }
    }
  },
  template: `
  <button v-on2:click="show">点击</button>
  `,
  methods: {
    show() {
      console.log("show");
    }
  }
}).$mount("#app");