vue3动态加载组件

1、原理:利用component实现组件动态渲染,要渲染的实际组件由 is prop 决定。

  • 当 is 是字符串,它既可以是 HTML 标签名也可以是组件的注册名。
  • 或者,is 也可以直接绑定到组件的定义。
  • 内置组件都可以传递给 is,但是如果想通过名称传递则必须先对其进行注册。
  • 如果将组件本身传递给 is 而不是其名称,则不需要注册。
    vue官方文档-component内置动态组件

2、代码具体实现

思路:在页面上注册组件,利用component及组件名称实现动态渲染。

<component :is="dialogComponents.get(componentName)" :key="componentName"></component>
<script lang="ts" setup>
import {
    
     ref, defineAsyncComponent } from 'vue'
const componentName = ref('') //保存需要加载的的组件名称
const dialogComponents = ref(new Map<string, any>())
dialogComponents.value.set(
	'OfficialWebsite',
	defineAsyncComponent(() => import('./components/OfficialWebsite.vue'))
)
dialogComponents.value.set(
	'InterfacePlatform',
	defineAsyncComponent(() => import('./components/InterfacePlatform/index.vue'))
)
</script>

猜你喜欢

转载自blog.csdn.net/qq_41839808/article/details/126932705