自定义插件
插件可以写成函数:
ts
import type { ElfUIAppPluginFn } from "@elfui/core";
export const focusPlugin: ElfUIAppPluginFn = (app) => {
app.directive("focus", {
mounted(el) {
(el as HTMLElement).focus();
},
});
};也可以写成对象:
ts
import type { ElfUIAppPluginObject } from "@elfui/core";
export const appPlugin: ElfUIAppPluginObject<{ appName?: string }> = {
install(app, options) {
if (options?.appName) {
app.config.globalProperties.appName = options.appName;
}
},
};App 实例
插件拿到的是 createApp() 创建的应用实例:
| 成员 | 作用 |
|---|---|
app.directive(name, def) | 注册当前 App 的指令;同名指令不会和其它 App 串用 |
app.component(component) | 确保组件按自身编译期 tag 注册到浏览器 customElements 全局注册表 |
app.provide(key, value) | 注入应用级依赖 |
app.config | 应用级配置 |
WARNING
同一个 app 实例中,同一个插件对象只会安装一次。provide/config/directive 按 App 隔离;Custom Element 的 tag 由浏览器全局注册表管理,因此不同 App 不能为同一 tag 注册不同构造器。
清理 App 级资源
插件可以返回同步清理函数。app.unmount() 会先卸载根组件,再按后安装先清理的顺序执行插件清理:
ts
export const keyboardPlugin: ElfUIAppPluginFn = () => {
window.addEventListener("keydown", onKeydown);
return () => window.removeEventListener("keydown", onKeydown);
};清理只执行一次。某个清理函数抛错时,错误会交给 app.config.errorHandler,其余插件仍继续清理。
