自定义指令
自定义指令适合封装 DOM 行为,比如自动聚焦、权限隐藏、第三方库挂载。
全局指令
ts
import { createApp } from "@elfui/core";
const app = createApp(App);
app.directive("focus", {
mounted(el) {
(el as HTMLElement).focus();
}
});
app.mount("#app");app.directive() 只对当前 App 生效。ElfUI 不再公开进程级全局指令注册表,避免互不相关的 App 之间发生指令泄漏。
模板中使用:
html
<input v-focus />局部指令
宏组件中使用 defineDirective():
ts
import { defineDirective } from "@elfui/core";
const focus = defineDirective<unknown, HTMLInputElement>({
mounted(el) {
el.focus();
}
});defineDirective() 必须赋值给本地变量,变量名就是模板指令名;camelCase 会转换为 kebab-case,例如 const autoFocus 对应 v-auto-focus。组件编译器会优先解析局部定义,再查找当前 App 的指令注册表。当行为属于单个组件实现时,应使用局部指令。
生命周期
指令支持:
| Hook | 时机 |
|---|---|
mounted | 元素挂载后 |
updated | 绑定值更新后 |
beforeUnmount | 元素卸载前 |
unmounted | 元素卸载时 |
TIP
如果行为涉及组件状态,优先考虑内置组合式函数;如果行为只关心某个 DOM 元素,指令更合适。
