vue3.0破坏性变化----自定义指令API的变化

vue3中指令api和组件保持一致,具体表现在:

  • bind → beforeMount
  • inserted→mounted
  • beforeUpdate: new! 元素自身更新前调用,和组件生命周期钩子很像
  • update→removed!和udpated基本相同,因此被移除,使用updated代替
  • componentUpdated → updated
  • beforeUnmount :new!和组件生命周期钩子相似,元素将要被移除之前调用
  • unbind → unmounted

vue 2.0指令使用
<template>
  <div>
    <h1>自定义指令</h1>
    <input type="text" v-autofoucs="true" placeholder="测试自定义指令" />
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  directives: {
    autofoucs: {
      // 参数:el,binding,vnode,oldVnode
      bind() {
        console.log("bind");
      },
      inserted(el, { value }, vnode, oldVnode) {
        console.log("inserted", el, vnode, oldVnode);
        if (value) {
          el.focus();
        }
      },

      update() {
        console.log("update");
      },
      componentUpdated() {
        console.log("componentUpdated");
      },
      unbind() {
        console.log("unbind");
      },
    },
  },
};
</script>
vue3.0指令使用
<template>
  <h1>自定义指令</h1>
  <input type="text" v-autoFocus v-model="text" />
</template>
<script lang='ts'>
import { defineComponent } from "vue";
export default defineComponent({
  data() {
    return { text: "这是一段文本" };
  },
  directives: {
    autoFocus: {
     // 参数:el,binding,vnode,oldVnode
      beforeMount() {
        console.log("beforeMount");
      },
      mounted() {
        console.log("mounted");
      },
      beforeUpdate() {
        console.log("beforeUpdate");
      },
      updated() {
        console.log("updated");
      },
      beforeUnmount() {
        console.log("beforeUnmount");
      },
      unmounted() {
        console.log("unmounted");
      },
    },
  },
});
</script>
<style scoped>
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容