Vue3 dynamically loads components

1. Principle: Use component to realize dynamic rendering of components, and the actual component to be rendered is determined by is prop.

  • When is is a string, it can be either an HTML tag name or a registered component name.
  • Alternatively, is can also be bound directly to the component definition.
  • Built-in components can be passed to is, but if you want to pass by name, you must first register it.
  • If you pass the component itself to is instead of its name, no registration is required.
    Vue official documentation - component built-in dynamic components

2. Code implementation

Idea: Register components on the page, and use component and component name to achieve dynamic rendering.

<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>

Guess you like

Origin blog.csdn.net/qq_41839808/article/details/126932705