I find in Vue3 Type Declaration about Directive
, it is this
export declare type Directive<T = any, V = any> = ObjectDirective<T, V> | FunctionDirective<T, V>;
I believe most people are familiar with 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;
}
But what's the 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;
I tried to find some useful infomation about it in offical documentation, but no gained.
So who can tell me what's this and how to use it?
CodePudding user response:
There 2 ways to declare a Vue directive - using an object syntax, where you declare all the hooks that your directive is interested in and a functional syntax, where you pass a function and that function is used for mounted
and updated
hooks
So declaring the directive using:
const hook = (el, binding) => {
// do some stuff
}
app.directive('my-directive', hook)
...is same as:
const hook = (el, binding) => {
// do some stuff
}
app.directive('my-directive', {
mounted: hook,
updated: hook,
})