模板引用
useTemplateRef() 用来拿到模板中的 DOM 节点。
ts
const input = useTemplateRef<HTMLInputElement>("input");
const focus = (): void => {
input.value?.focus();
};
export const SearchInput = defineHtml(`
<input ref="input" />
<button @click=${focus}>聚焦</button>
`);和组件暴露配合
ts
defineExpose({ focus }, { overrideNative: ["focus"] });父组件或外部页面拿到组件 host 后即可调用 focus()。父组件的 onMounted() 会在同步子组件 完成 setup、expose 和 mounted 之后运行,因此可以在该阶段稳定调用子组件公开方法:
ts
const search = useTemplateRef<HTMLElement & { focus(): void }>("search");
onMounted(() => {
search.value?.focus();
});详见“组件 / 组件暴露”。
