Skip to content

动态组件

动态组件用于在运行时切换要渲染的组件。

ts
import { defineHtml, useRef } from "@elfui/core";
import { UserCard } from "./UserCard";
import { TeamCard } from "./TeamCard";

const current = useRef<typeof UserCard | typeof TeamCard>(UserCard);

export const Dashboard = defineHtml(` <component :is=${current}></component> `);

:is 可以是组件构造器,也可以是已经注册的标签名。

ts
const current = useRef("elf-user-card");

配合 KeepAlive

需要缓存实例时,用 <KeepAlive> 包住动态组件:

html
<KeepAlive>
  <component :is="current"></component>
</KeepAlive>

适合 tab、路由页、编辑器面板等切换频繁但不希望重建状态的场景。