vue-11-自定义指令

用于对纯 DOM 元素进行底层操作。

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

简写:

Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})

钩子函数:

  • bind只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。

  • inserted被绑定元素插入父节点时调用 (父节点存在即可调用,不必存在于 document 中)。

  • update所在组件的 VNode 更新时调用,但是可能发生在其孩子的 VNode 更新之前。指令的值可能发生了改变也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。

  • componentUpdated所在组件的 VNode 及其孩子的 VNode 全部更新时调用。

  • unbind只调用一次,指令与元素解绑时调用。

钩子函数的参数 (包括 elbindingvnodeoldVnode)

<div id="hook-arguments-example" v-demo:foo.a.b="message"></div>

Vue.directive('demo', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: '       + s(binding.name) + '<br>' + //指令名 "demo"
      'value: '      + s(binding.value) + '<br>' +//指令的绑定值 "hello!"
      'expression: ' + s(binding.expression) + '<br>' +//绑定值的字符串形式 "message"
      'argument: '   + s(binding.arg) + '<br>' +//传给指令的参数 "foo"
      'modifiers: '  + s(binding.modifiers) + '<br>' +//一个包含修饰符的对象 {"a":true,"b":true}
      'vnode keys: ' + Object.keys(vnode).join(', ')+//Vue 编译生成的虚拟节点
    //'oldVnode: ' + Object.keys(oldVnode).join(', ')//上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。 }
})
new Vue({ el: '#hook-arguments-example', data: { message: 'hello!' } })

对象字面量

<div v-demo="{ color: 'white', text: 'hello!' }"></div>//指令绑定的值

Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
})
原文地址:https://www.cnblogs.com/avidya/p/7640862.html