自定义指令

69 阅读1分钟

自定义指令

  • 作用:为元素添加特殊的效果
  • 设置:使用 directive 定义
  • 使用:v-directive中定义的函数名称
<template>
  <!-- 指令的使用 -->
  <h2 v-color="'pink'">APP</h2>
  <h2 v-color="bgColor">。。。。。</h2>
</template>

<script>
export default {
  data() {
    return {
      bgColor: "orange",
    };
  },
  directives: {
    // 自定义指令
    /* 
    color: {
        // 挂载完成后执行
      mounted(el, binding) {
        el.style.backgroundColor = binding.value;
      },
        // 每次更新后执行
      updated(el, binding) {
        el.style.backgroundColor = binding.value;
      },
    }, 
    */

    // 简写
    color(el, binding) {
      el.style.backgroundColor = binding.value;
    },
  },
};
</script>