组件暴露
defineExpose() 把方法或属性暴露到组件 host 上,外部可以通过 DOM ref 调用。
ts
import { defineExpose, defineHtml, useTemplateRef } from "@elfui/core";
const input = useTemplateRef<HTMLInputElement>("input");
defineExpose(
{
focus: () => input.value?.focus(),
clear: () => {
if (input.value) input.value.value = "";
}
},
{ overrideNative: ["focus"] }
);
export const SearchInput = defineHtml(` <input ref="input" /> `);需要把公开实例契约复用到类型声明时,也可以显式传入有限键接口;接口不需要额外声明字符串索引签名:
ts
interface SearchInputExpose {
focus(): void;
clear(): void;
}
defineExpose<SearchInputExpose>({ focus, clear }, { overrideNative: ["focus"] });与 HTMLElement 原生成员冲突
公开名称如果已经存在于组件 host 上,框架会在开发态给出警告。只有组件确实需要增强原生 语义时才使用 overrideNative:
ts
defineExpose(
{ focus, blur },
{ overrideNative: ["focus", "blur"] }
);scrollTo()、remove()、click() 等名称通常不应覆盖,优先使用 scrollToOption()、removeItem()、triggerAction() 等组件语义名称。
外部使用:
ts
const el = document.querySelector("search-input") as HTMLElement & {
focus(): void;
};
// 外部可以调用暴露的方法
el.focus();适合暴露什么
适合暴露命令式能力:
focus()blur()validate()reset()scrollToActive()
WARNING
不要暴露内部响应式状态。状态应该通过 props、事件或 v-model 维护。
