美文网首页
vue动态引入组件,在引入组件之前判断组件是否存在,存在则引入

vue动态引入组件,在引入组件之前判断组件是否存在,存在则引入

作者: 瓩千瓦 | 来源:发表于2021-11-25 18:18 被阅读0次

主要使用webpack中require.context方法

/* 
require.context(directory, useSubdirectories, regExp)
directory: 要查找的文件路径  
useSubdirectories: 是否查找子目录
regExp: 要匹配文件的正则
*/ 
import demandRelatedDefect from "@/components/demand/demand-related-defect.vue"; //基础静态组件

// import NonFunctionalSafety from "@/components/demand/Non-functional-safety.vue"; //需要引入动态组件的正常写法

let components = {
  demandRelatedDefect
}

//找到components文件夹下以.vue命名的文件
const introductions = require.context('@/components/customization/demand/', true, /\.vue$/); // 返回值是函数
const introductionsLength = introductions.keys(); // 返回值是个数组["./A.js", "./B.js", "./C.js", "./D.js"]
if(introductionsLength.length){ // 路径./app/ 包含 .vue文件
  introductionsLength.forEach(fileName => { //遍历组件
    const componentConfig = introductions(fileName); //动态引入 ./app/Non-functional-safety.vue
    console.log(fileName)
    components['NonFunctionalSafety'] = componentConfig.default || componentConfig;  //注册组件
  });
}


export default {
  name: 'demand-detail',
  components: components
  /* components: { //静态写法
    demandRelatedDefect, demandRelatedDefect
  } */
}

相关文章

网友评论

      本文标题:vue动态引入组件,在引入组件之前判断组件是否存在,存在则引入

      本文链接:https://www.haomeiwen.com/subject/ylkztrtx.html