指令

作用:操作dom
钩子函数:HOOK

bind:只在绑定的时候调用一次
inserted: 插入到父元素的时候调用
update: 容器组件更新,有可能还没跟新,可以通过比较跳过不必要的值
componentUpdated:容器或者子元素跟新时候调用
unbind: 取消绑定的时候调用

钩子函数参数:

le:dom 元素
binding: object
{
   name: directive 的名字
   value: 传递的值 ,如 v-my-directive="1 + 1"  value= 2
   oldValue: 之前的值 in update and componentUpdated
   expression: 表达式 如 inv-my-directive="1 + 1"结果为 "1 + 1"
   arg: 传递给指令的参数, if any. 如v-my-directive:foo,结果 "foo"
   modifiers: 如v-my-directive.foo.bar, 结果{ foo: true, bar: true }
}
vnode: vnode 节点
oldVnode: 之前的 virtual node, 只在 update 和 componentUpdated hooks

demo

<div id="hook-arguments-example" v-demo:hello.a.b="message"></div>
Vue.directive('demo', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: '       + s(binding.name) + '<br>' +
      'value: '      + s(binding.value) + '<br>' +
      'expression: ' + s(binding.expression) + '<br>' +
      'argument: '   + s(binding.arg) + '<br>' +
      'modifiers: '  + s(binding.modifiers) + '<br>' +
      'vnode keys: ' + Object.keys(vnode).join(', ')
  }
})
new Vue({
  el: '#hook-arguments-example',
  data: {
    message: 'hello!'
  }
})
Paste_Image.png

如果只关心bind and update

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

如果传递的参数是对象

<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!"
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容