vue動態(tài)引入組件、批量引入組件方式(vue2,vue3)
更新時間:2026年02月10日 09:31:20 作者:無心使然云中漫步
文章總結(jié)了Vue 2和Vue 3中批量引入組件的方法,并詳細說明了如何在模板中使用動態(tài)組件`component`根據(jù)key值渲染組件,文章還提供了一個示例函數(shù)來處理路徑,并將組件動態(tài)引入到`componentList`中
vue2
批量全局引入:
import Vue from "vue"
const components = require.context(
'./', //組件所在目錄的相對路徑
false, //是否查詢其子目錄
/[A-Z]\w+\.(vue|js)$/ //匹配組件文件名的正則表達式
)
components.keys().forEach(fileName=>{
// 獲取文件名
var names = fileName.split("/").pop().replace(/\.\w+$/,"");
// 獲取組件配置
const comp = components(fileName);
// 若該組件是通過"export default"導出的,優(yōu)先使用".default",
// 否則退回到使用模塊的根
Vue.component(names,comp.default || comp);
})
批量局部引入:
<script>
// 引入所有需要的動態(tài)組件
const components = require.context(
"./", //組件所在目錄的相對路徑
true, //是否查詢其子目錄
/\w+.vue$/ //匹配基礎(chǔ)組件文件名的正則表達式
);
const comObj = {};
components.keys().forEach(fileName => {
// 獲取文件名
var names = fileName.split("/").pop().replace(/.\w+$/, "");
// 獲取組件配置
const comp = components(fileName);
// 若該組件是通過"export default"導出的,優(yōu)先使用".default",否則退回到使用模塊的根
comObj[names] = comp.default || comp;
});
export default {
data() {
return {
}
},
mounted() {},
components: comObj
};
</script>
vue3
批量引入:
批量導入組件,在模板中利用動態(tài)組件component,根據(jù)key值渲染組件,注意這里的key類似‘./components/Component1.vue’這樣的形式,如果需要去掉路徑可以用函數(shù)處理再放入componentList
<template>
<component :is="componentList[componentName]"></component>
</template>
<script lang="ts" setup>
const componentList: Record<string, any> = reactive({});
const components = import.meta.glob('./components/**/*.vue');
Object.entries(components).forEach(async ([key, val]) => {
componentList[key] = defineAsyncComponent(val);
});
const props = defineProps({
componentName: {
type: String,
default: '',
},
});
</script>
動態(tài)引入:
<template>
<component :is="componentName"></component>
</template>
<script lang="ts" setup>
const props = defineProps({
componentName: {
type: String,
default: '',
},
});
const comp = defineAsyncComponent(() => import(`./components/${props.componentName}.vue`));
</script>
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue 基于abstract 路由模式 實現(xiàn)頁面內(nèi)嵌的示例代碼
這篇文章主要介紹了vue 基于abstract 路由模式 實現(xiàn)頁面內(nèi)嵌的示例代碼,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12
Vue3處理大數(shù)據(jù)量渲染和優(yōu)化的方法小結(jié)
在現(xiàn)代Web應(yīng)用中,隨著用戶數(shù)據(jù)和交互的復(fù)雜性增加,如何高效地處理大數(shù)據(jù)量渲染成為了前端開發(fā)的重要環(huán)節(jié),本文將以Vue 3為例,探討如何優(yōu)化大數(shù)據(jù)量渲染,提升應(yīng)用性能,需要的朋友可以參考下2024-07-07
解決Antd中Form表單的onChange事件中執(zhí)行setFieldsValue不生效
這篇文章主要介紹了解決Antd中Form表單的onChange事件中執(zhí)行setFieldsValue不生效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

