vue中组件加载

140 阅读1分钟

参考 blog.csdn.net/weixin_4511…

  • 组件的按需加载
components: {
    TreeDemo: () => import('@/components/TreeDemo.vue'),
  },
 <component :is="activeComponent"/>
 
watch: {
    /**
     * @desc 监听tab的变化 加载对应的组件
     * @param {componentName}  当前激活的tab name === 组件名
     */
    activeTabValue: {
      handler(componentName) {
        console.log('watch---activeTabValue---start');
        if (!componentName) return
        const fileName = componentName[0].toLowerCase() + componentName.slice(1)
        
        // import(`./${fileName}/${componentName}.vue`).then(component => {
        //   this.activeComponent = component.default
        // })
        
        // webpack 中动态import不支持以变量的方式,替换为下面的代码(不然测试环境会有问题)
        this.activeComponent = (resolve) => require([`./${fileName}/${componentName}.vue`], resolve)
      },
      immediate: true
    }
},
  • webpack加载某个目录下的指定类型的文件
// require.context('目录','是否要查找该目录下的子级目录', '以某某结尾的文件')
const allComponents = require.context("./components", true, /.vue$/);
const components = {};

allComponents.keys().forEach((item) => {
    const component = allComponents(item);
    const name = component.default.name;
    components[name] = component.default;
});

export default {
  components: { ...components },
}