vue動(dòng)態(tài)引入組件、批量引入組件方式(vue2,vue3)
vue2
批量全局引入:
import Vue from "vue"
const components = require.context(
'./', //組件所在目錄的相對路徑
false, //是否查詢其子目錄
/[A-Z]\w+\.(vue|js)$/ //匹配組件文件名的正則表達(dá)式
)
components.keys().forEach(fileName=>{
// 獲取文件名
var names = fileName.split("/").pop().replace(/\.\w+$/,"");
// 獲取組件配置
const comp = components(fileName);
// 若該組件是通過"export default"導(dǎo)出的,優(yōu)先使用".default",
// 否則退回到使用模塊的根
Vue.component(names,comp.default || comp);
})
批量局部引入:
<script>
// 引入所有需要的動(dòng)態(tài)組件
const components = require.context(
"./", //組件所在目錄的相對路徑
true, //是否查詢其子目錄
/\w+.vue$/ //匹配基礎(chǔ)組件文件名的正則表達(dá)式
);
const comObj = {};
components.keys().forEach(fileName => {
// 獲取文件名
var names = fileName.split("/").pop().replace(/.\w+$/, "");
// 獲取組件配置
const comp = components(fileName);
// 若該組件是通過"export default"導(dǎo)出的,優(yōu)先使用".default",否則退回到使用模塊的根
comObj[names] = comp.default || comp;
});
export default {
data() {
return {
}
},
mounted() {},
components: comObj
};
</script>
vue3
批量引入:
批量導(dǎo)入組件,在模板中利用動(dòng)態(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>
動(dòng)態(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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)廣告欄上下滾動(dòng)效果
這篇文章主要介紹了vue實(shí)現(xiàn)廣告欄上下滾動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
vue 基于abstract 路由模式 實(shí)現(xiàn)頁面內(nèi)嵌的示例代碼
這篇文章主要介紹了vue 基于abstract 路由模式 實(shí)現(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不生效問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03

