Vue3 dynamically loads components, dynamically imports components

1. Problems
When working on a project that viteis built with a user, the imported page is vue3dynamically pulled , and then the console keeps showing the following prompts, and the page cannot be rendered. 2. Analysis According to the above error message, let us install and use: this plug-in (there is no such solution in the end)..vue
insert image description here

@rollup/plugin-dynamic-import-vars

The official Vite document says that you need to use the Glob import form , and then read a Glob document to solve this problem (probable test).

import.meta.globFirst you need to import multiple modules from the file system using special functions:

const modules = import.meta.glob('../views/*/*.vue');

It will match and import all relevant components:

// vite 生成的代码
const modules = {
    
    
  './views/foo.vue': () => import('./views/foo.vue'),
  './views/bar.vue': () => import('./views/bar.vue')
}

Then go back to the project and import all the files homeunder the folder into the files under the folder . Therefore, according to the function of vite : you can get the files under the corresponding folderindex.vuecustom_components.vue
insert image description here
import.meta.globcustom_components.vue

const changeComponents = (e:string)=>{
    
    
	const link = modules[`../custom_components/${
      
      e}.vue`]
	console.log(link,'link')
}

linkYou can see by printing
insert image description here
that the last is the asynchronous registration component

layouts.value = markRaw(defineAsyncComponent(link))

3. Finally,
the complete case is posted below for reference only. If there are better ones or those that need to be optimized, you can ask questions and discuss them together.

<template>	
	<div @click="changeComponents('kk')">显示kk.vue</div>
	<div @click="changeComponents('index')">显示index.vue</div>
	<component :is="layouts"/>
</template>

<script lang='ts' setup>
	const modules = import.meta.glob('../custom_components/*.vue');
	let layouts = ref<any>(null)
	const changeComponents = (e:string)=>{
    
    
		const link = modules[`../custom_components/${
      
      e}.vue`]
        layouts.value = markRaw(defineAsyncComponent(link))
	}
</script>

Guess you like

Origin blog.csdn.net/xixihahakkyy/article/details/128965295