fncheng / vue-learn

0 stars 0 forks source link

Vue自定义指定directives #17

Open fncheng opened 3 years ago

fncheng commented 3 years ago

Directive

文档

全局:

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})

局部:

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

Hook

一个指令定义对象可以提供如下几个钩子函数 (均为可选):

Hook function params

1.如果需要在自定义指令中调用传入的函数,通过binding.value 可以取到传入的函数,在hook中调用=> binding.value()。 demo:

directives: {
    lazyload: {
      bind(el, binding, vnode) {
        let cb = binding.value
        console.log(Object.prototype.toString.call(cb))

        let observer = new IntersectionObserver(cb)
        observer.observe(el)
      },
    },
  }

2.在directives中拿this 通过第三个参数vnode

vnode.context 就是Vue实例this