【问题标题】:How to use FunctionDirective in Vue3?如何在 Vue 3 中使用函数指令?
【发布时间】:2022-01-07 14:43:02
【问题描述】:

我在 Vue3 类型声明中找到了 Directive,就是这个

export declare type Directive<T = any, V = any> = ObjectDirective<T, V> | FunctionDirective<T, V>;

相信大多数人都熟悉ObjectDirective

export declare interface ObjectDirective<T = any, V = any> {
    created?: DirectiveHook<T, null, V>;
    beforeMount?: DirectiveHook<T, null, V>;
    mounted?: DirectiveHook<T, null, V>;
    beforeUpdate?: DirectiveHook<T, VNode<any, T>, V>;
    updated?: DirectiveHook<T, VNode<any, T>, V>;
    beforeUnmount?: DirectiveHook<T, null, V>;
    unmounted?: DirectiveHook<T, null, V>;
    getSSRProps?: SSRDirectiveHook;
    deep?: boolean;
}

但是FunctionDirective 是什么?

export declare type FunctionDirective<T = any, V = any> = DirectiveHook<T, any, V>;

export declare type DirectiveHook<T = any, Prev = VNode<any, T> | null, V = any> = (el: T, binding: DirectiveBinding<V>, vnode: VNode<any, T>, prevVNode: Prev) => void;

我试图在官方文档中找到一些有用的信息,但没有任何收获。

那么谁能告诉我这是什么以及如何使用它?

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    2 ways to declare a Vue directive - 使用对象语法,在其中声明指令感兴趣的所有钩子和函数语法,在其中传递函数,该函数用于 mountedupdated 钩子

    所以声明指令使用:

    const hook = (el, binding) => {
      // do some stuff
    }
    
    app.directive('my-directive', hook)
    

    ...等同于:

    const hook = (el, binding) => {
      // do some stuff
    }
    
    app.directive('my-directive', {
      mounted: hook,
      updated: hook,
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2021-01-14
      • 2021-01-31
      • 2021-02-03
      • 1970-01-01
      • 2019-01-22
      • 2022-10-06
      相关资源
      最近更新 更多