1.問題
在做一個用vite
構(gòu)建的vue3
項目時,動態(tài)拉取導(dǎo)入.vue
頁面,然后控制臺一直有以下提示,頁面也無法渲染出來。
2.分析
根據(jù)上面的報錯提示,讓我們安裝并使用:@rollup/plugin-dynamic-import-vars
這個插件(最終沒有這個方案)。
Vite官方文檔說需要使用Glob 導(dǎo)入形式,然后看了一個Glob的文檔,解決了這個問題(親測可行)。
首先需要使用特殊的import.meta.glob
函數(shù)從文件系統(tǒng)導(dǎo)入多個模塊:
const modules = import.meta.glob('../views/*/*.vue');
他會匹配并導(dǎo)入所有相關(guān)的組件:
// vite 生成的代碼
const modules = {
'./views/foo.vue': () => import('./views/foo.vue'),
'./views/bar.vue': () => import('./views/bar.vue')
}
那么回到項目中,在home
文件夾下的index.vue
文件中導(dǎo)入custom_components
文件夾下的所有.vue
文件
因此,根據(jù)vite的import.meta.glob
函數(shù):就可以獲得對應(yīng)的custom_components
文件夾下的.vue
文件
const changeComponents = (e:string)=>{
const link = modules[`../custom_components/${e}.vue`]
console.log(link,'link')
}
打印link
可以看到
最后就是異步注冊組件文章來源:http://www.zghlxwxcb.cn/news/detail-406383.html
layouts.value = markRaw(defineAsyncComponent(link))
3.最后
下面貼出完整案例,僅供參考。有更好的或者需要優(yōu)化的可以提問一起探討。文章來源地址http://www.zghlxwxcb.cn/news/detail-406383.html
<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>
到了這里,關(guān)于vue3 動態(tài)加載組件、動態(tài)引入組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!