vue自定义指令

133 阅读1分钟

为什么会使用自定义指令?

当vue中内置的默认指令不足以处理业务的时候,可以自定义指令。 例如,想要对普通的DOM元素进行底层操作时,这个时候就会使用自定义指令。

注册自定义指令

  • 作用:

    • 获取标签 -扩展额外的功能
  • inserted方法 - 指令所在标签, 被插入到网页上触发(一次)

  • update方法 - 指令对应数据/标签更新时, 此方法执行

全局注册和使用

  • 在main.js使用 Vue.directive()方法来进行注册。 可以在任意的.vue文件里都可以直接用v-color指令。

  • 自定义指令也可以传值

  • 语法:

Vue.directive("自定义指令名", {
  inserted(el) {
     // 触发标签的事件方法
  }
})
Vue.directive("color", {
    inserted(el, binding) {
        console.log('inserted');
        console.log(el, binding);
        // el.style.color = 'pink'
        el.style.color = binding.value
    },
    update(el, binding) {
        console.log('update');
        console.log(el, binding);
        el.style.color = binding.value
    }
})

局部注册和使用

  • 作用:只能在当前的vue文件中使用
  • 语法:
 directives: {
            自定义指令:{
              inserted(el){
                console.log(el);
              }
            }
          }
  • 注册一个局部自定义字体大小的指令:
<template>
  <div>
    <h1 v-size>自定义指令</h1>
  </div>
</template>

<script>
export default {
  // 局部自定义指令
  directives: {
    size:{
      inserted(el){
        console.log(el);
        el.style.fontSize="100px"
      }
    }
  }
}
</script>

<style>

</style>