欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > 在 Vue 3 的 Composition API 中,如何实现动态组件

在 Vue 3 的 Composition API 中,如何实现动态组件

2025/2/27 8:43:59 来源:https://blog.csdn.net/qq_35940731/article/details/145868518  浏览:    关键词:在 Vue 3 的 Composition API 中,如何实现动态组件

在 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>
代码解释:
  1. 导入组件:使用 import 语句将需要动态切换的组件引入。
  2. 创建响应式数据:借助 ref 创建 currentComponent 响应式变量,其初始值为 'ComponentA',用于存储当前要显示的组件名。
  3. 动态组件渲染<component :is="currentComponent" /> 标签中的 :is 绑定 currentComponent,Vue 会根据该变量的值动态渲染对应的组件。
  4. 按钮切换:点击按钮时,通过修改 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>
代码解释:
  1. 定义异步组件:使用 defineAsyncComponent 函数结合 import() 语法动态导入组件,实现异步加载。
  2. 使用 <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 中实现动态组件的基础切换、异步加载以及状态缓存等功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词