vue動態(tài)引入組件,在引入組件之前判斷組件是否存在,存在則引入

主要使用webpack中require.context方法

/* 
require.context(directory, useSubdirectories, regExp)
directory: 要查找的文件路徑  
useSubdirectories: 是否查找子目錄
regExp: 要匹配文件的正則
*/ 
import demandRelatedDefect from "@/components/demand/demand-related-defect.vue"; //基礎(chǔ)靜態(tài)組件

// import NonFunctionalSafety from "@/components/demand/Non-functional-safety.vue"; //需要引入動態(tài)組件的正常寫法

let components = {
  demandRelatedDefect
}

//找到components文件夾下以.vue命名的文件
const introductions = require.context('@/components/customization/demand/', true, /\.vue$/); // 返回值是函數(shù)
const introductionsLength = introductions.keys(); // 返回值是個數(shù)組["./A.js", "./B.js", "./C.js", "./D.js"]
if(introductionsLength.length){ // 路徑./app/ 包含 .vue文件
  introductionsLength.forEach(fileName => { //遍歷組件
    const componentConfig = introductions(fileName); //動態(tài)引入 ./app/Non-functional-safety.vue
    console.log(fileName)
    components['NonFunctionalSafety'] = componentConfig.default || componentConfig;  //注冊組件
  });
}


export default {
  name: 'demand-detail',
  components: components
  /* components: { //靜態(tài)寫法
    demandRelatedDefect, demandRelatedDefect
  } */
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容