Vue.directive自定义指令

<template>
  <div class="hello">
    <div class="" v-wht="color">{{ num }}</div>
    <!-- <div class="" v-jswht="color">{{ num }}</div> -->
    <button @click="add()">点我啊</button>
  </div>
</template>

<script>
import Vue from "vue";
//bind: 只调用一次,指令第一次绑定到元素时调用,可以定义一个在绑定时执行一次的初始化动作。
//inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
//update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值。
//componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
//unbind: 只调用一次, 指令与元素解绑时调用。
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      num: 0,
      color: "yellow"
    };
  },
  methods: {
    add() {
      this.num++;
    }
  }
};
// 注册 (指令函数)
Vue.directive(
  "wht",
  // function(el, binding) {
  // 	el.style.color = binding.value;
  // }
  {
    bind: function() {
      //只调用一次
      console.log("1-只调用一次");
    },
    inserted: function() {
      //插入节点
      console.log("2-插入");
    },
    update: function() {
      //组件更新
      console.log("3-组件更新");
    },
    componentUpdated: function() {
      //组件更新完成
      console.log("4 - 组件更新完成");
    }
  }
);
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

Vue.directive大神封装:https://github.com/Michael-lzg/v-directives/blob/master/README.md

原文地址:https://www.cnblogs.com/hanhaiyuntao/p/14183079.html