1. Problems
When working on a project that vite
is built with a user, the imported page is vue3
dynamically 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
@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.glob
First 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 home
under the folder into the files under the folder . Therefore, according to the function of vite : you can get the files under the corresponding folderindex.vue
custom_components
.vue
import.meta.glob
custom_components
.vue
const changeComponents = (e:string)=>{
const link = modules[`../custom_components/${
e}.vue`]
console.log(link,'link')
}
link
You can see by printing
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>