Vue3之自定义指令directive

422 阅读1分钟
  • Vue3自定义指令的钩子

  • created 元素初始化的时候

  • created 元素初始化的时候

  • mounted 元素插入父级dom调用

  • beforeUpdate 元素被更新之前调用

  • update 这个周期方法被移除 改用updated

  • beforeUnmount 在元素被移除前调用

  • unmounted 指令被移除后调用 只调用一次

  • Vue2 指令 bind inserted update componentUpdated unbind

在setup内定义局部指令

  • 自定义指令 必须以vNameOfDirective 的形式来命名本地自定义组件,以使得他们可以直接在模板中使用
<DirectiveDemo v-if="flag" v-move-directive="{background: 'red'}"></DirectiveDemo>
<script setup lang="ts">
    import { Directive, DirectiveBinding, reactive, ref } from 'vue';
    type Value = {
      background: string;
    }
    
    const flag = ref(false)
    
    const handleChange = () => {
      flag.value = !flag.value
    }
    
    const vMoveDirective: Directive = {
      created: () => {
        console.log("created====>");
      },
      beforeMount(...args: Array<any>) {
        // 在元素上做些操作
        console.log("beforeMount=======>");
      },
      mounted(el: HTMLElement, dir: DirectiveBinding<Value>) {
        // 组件挂载之后做某事
        el.style.background = dir.value.background;
        console.log("mounted========>");
      },
      // 数据变更触发
      beforeUpdate() {
        console.log("beforeUpdate");
      },
      updated() {
        console.log("updated");
      },
      beforeUnmount(...args: Array<any>) {
        console.log(args);
        console.log("======>beforeUnmount");
      },
      unmounted(...args: Array<any>) {
        console.log(args);
        console.log("======>unmounted");
      },
    };
</script>

生命周期钩子参数详解

第一个 el  当前绑定的DOM 元素

  • instance:使用指令的组件实例。
  • value:传递给指令的值。例如,在 v-my-directive="1 + 1" 中,该值为 2
  • oldValue:先前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否有更改都可用。
  • arg:传递给指令的参数(如果有的话)。例如在 v-my-directive:foo 中,arg 为 "foo"
  • modifiers:包含修饰符(如果有的话) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}
  • dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中

image.png

第二个 binding

binding 参数会是一个这样的对象

{
  arg: 'foo',
  modifiers: { bar: true },
  value: /* `baz` 的值 */,
  oldValue: /* 上一次更新时 `baz` 的值 */
}

第三个 当前元素的虚拟DOM 也就是Vnode

第四个 prevNode 上一个虚拟节点,仅在 beforeUpdate 和 updated 钩子中可用