在 Vue 3 的 Composition API 中,实现动态组件主要借助 <component>
标签结合 :is
动态绑定属性,同时搭配响应式数据来控制显示不同的组件。以下将从基础实现、加载异步组件以及组件缓存三个方面详细介绍实现动态组件的方法。
基础实现
<template><div><!-- 切换组件的按钮 --><button @click="currentComponent = 'ComponentA'">显示组件 A</button><button @click="currentComponent = 'ComponentB'">显示组件 B</button><!-- 动态组件 --><component :is="currentComponent" /></div>
</template><script setup>
import { ref } from 'vue';
// 引入需要的组件
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';// 使用 ref 创建响应式数据来存储当前要显示的组件名
const currentComponent = ref('ComponentA');// 注册组件,这样动态组件才能识别
const components = {ComponentA,ComponentB
};
</script>
代码解释:
- 导入组件:使用
import
语句将需要动态切换的组件引入。 - 创建响应式数据:借助
ref
创建currentComponent
响应式变量,其初始值为'ComponentA'
,用于存储当前要显示的组件名。 - 动态组件渲染:
<component :is="currentComponent" />
标签中的:is
绑定currentComponent
,Vue 会根据该变量的值动态渲染对应的组件。 - 按钮切换:点击按钮时,通过修改
currentComponent
的值来切换显示的组件。
加载异步组件
<template><div><button @click="currentComponent = 'AsyncComponentA'">显示异步组件 A</button><button @click="currentComponent = 'AsyncComponentB'">显示异步组件 B</button><Suspense><!-- 正常显示的组件 --><template #default><component :is="currentComponent" /></template><!-- 加载中的占位组件 --><template #fallback><div>加载中...</div></template></Suspense></div>
</template><script setup>
import { ref } from 'vue';
// 使用 defineAsyncComponent 定义异步组件
const AsyncComponentA = defineAsyncComponent(() => import('./AsyncComponentA.vue'));
const AsyncComponentB = defineAsyncComponent(() => import('./AsyncComponentB.vue'));const currentComponent = ref('AsyncComponentA');const components = {AsyncComponentA,AsyncComponentB
};
</script>
代码解释:
- 定义异步组件:使用
defineAsyncComponent
函数结合import()
语法动态导入组件,实现异步加载。 - 使用
<Suspense>
:<Suspense>
组件用于处理异步组件的加载状态,#default
插槽用于显示正常加载的组件,#fallback
插槽用于显示加载过程中的占位内容。
组件缓存
若要缓存动态组件的状态,可使用 <KeepAlive>
组件。
<template><div><button @click="currentComponent = 'ComponentA'">显示组件 A</button><button @click="currentComponent = 'ComponentB'">显示组件 B</button><!-- 缓存动态组件 --><KeepAlive><component :is="currentComponent" /></KeepAlive></div>
</template><script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';const currentComponent = ref('ComponentA');const components = {ComponentA,ComponentB
};
</script>
代码解释:
<KeepAlive>
组件:将<component>
标签包裹在<KeepAlive>
中,这样在切换组件时,被隐藏的组件状态会被缓存,再次显示时无需重新初始化。
通过以上方法,你可以在 Vue 3 的 Composition API 中实现动态组件的基础切换、异步加载以及状态缓存等功能。