Home > Article > Web Front-end > How to use vue3 dynamically loading components and dynamically introducing components
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.
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 .vue
File
Therefore, according to vite’s import.meta.glob
function: you can get the corresponding custom_components
.vue
File under the folder
const changeComponents = (e:string)=>{ const link = modules[`../custom_components/${e}.vue`] console.log(link,'link') }
Printlink
You can see
Finally it is asynchronous Register component
layouts.value = markRaw(defineAsyncComponent(link))
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('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>
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!