vue2 自定义指令22 directives 简写 全局自定义

    <p v-color="'red'">测试</p>
    <button @click="color = 'green'">改变 color 的颜色值</button>
 
 data() {
    return {
      color: 'blue'
    }
  },


// 私有自定义指令的节点 directives: { // 定义名为 color 的指令,指向一个配置对象 color: { // 当指令第一次被绑定到元素上的时候,会立即触发 bind 函数 // 形参中的 el 表示当前指令所绑定到的那个 DOM 对象 bind(el, binding) { console.log('触发了 v-color 的 bind 函数') el.style.color = binding.value }, // 在 DOM 更新的时候,会触发 update 函数 update(el, binding) { console.log('触发了 v-color 的 update 函数') el.style.color = binding.value } } }


简写:
  directives: {
    color(el, binding) {
       el.style.color = binding.value
    }
}

  全局自定义:

main:

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

  

 

posted @ 2022-12-14 17:00  文采呱呱  阅读(143)  评论(0编辑  收藏  举报