Home  >  Article  >  Web Front-end  >  How to use vue3 dynamically loading components and dynamically introducing components

How to use vue3 dynamically loading components and dynamically introducing components

王林
王林forward
2023-05-11 12:01:143433browse

1. Problem

When working on a vue3 project built with vite, dynamically pull and import the .vue page, and then The console keeps showing the following prompt, and the page cannot be rendered.

How to use vue3 dynamically loading components and dynamically introducing components

2. Analysis

According to the above error message, let us install and use: @rollup/plugin-dynamic-import-vars This plug-in (there is no such solution in the end).

The Vite official document says that needs to use the Glob import form, and then I read a Glob document and solved this problem (personal test is feasible).

First you need to use the special import.meta.glob function to import multiple modules from the file system:

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

He will match and import all related 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 under the custom_components folder into the index.vue file under the home folder .vueFile

How to use vue3 dynamically loading components and dynamically introducing components

Therefore, according to vite’s import.meta.glob function: you can get the corresponding custom_components.vueFile under the folder

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

PrintlinkYou can see

How to use vue3 dynamically loading components and dynamically introducing components

Finally it is asynchronous Register component

layouts.value = markRaw(defineAsyncComponent(link))

3. Finally

The complete case is posted below for reference only. If there is anything better or needs optimization, you can ask questions and discuss them together.

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

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

The above is the detailed content of How to use vue3 dynamically loading components and dynamically introducing components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete