根据路由动态注册组件失败

动态注册组件

方式1 import

这种跟webpack的版本有关系 import低版本不支持传入动态参数

复制代码
<template>
        <components :is="componentName" v-show="isShow" :key="componentName"></components>
</template>


const _import = file => () => import(/* webpackChunkName: `[request][index]` */ `@/pages${file}/index.vue`);

let async = _import(path);
let timer = setTimeout(() => {
    async().then(com => {
  
        Vue.component(name, com.default);
        this.componentName = name;
        this.prevPath = path;
        this.isShow = true
    },
    errors => {
        this.componentName = Error;
        this.$message.error(
            `模块地址加载失败,地址:${path},具体错误:${errors}`
        );
        console.error(errors);
    });
})

方式2 require

这种方式能引入组件成功,并且能打印出com.default。但是刷新页面的时候会出现报错(可能是各种插件的版本导致)

复制代码
<template>
        <components :is="componentName" v-show="isShow" :key="componentName"></components>
</template>



let timer = setTimeout(() => {
    require([`@/views${path}/index.vue`], (com) => {
          Vue.component(name, com.default)
           this.componentName = name;
       },(errors)=>{
         this.$message.error(
               `模块地址加载失败,地址:${path},具体错误:${errors}`
           );
           console.error(errors);
       })
})

解决:替换Vue.component()

复制代码
 Vue.component(name, com.default)
 替换成
this.$options.components[name] = com.default
相关推荐
Penge66614 分钟前
Sass 了解
前端
Penge66627 分钟前
Webpack 打包从 0 到 1 实战笔记
前端
Penge66637 分钟前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6661 小时前
Ant Design(Antd)了解
前端
wangruofeng1 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge6662 小时前
JavaScript 核心语法速通
前端
wangruofeng3 小时前
写给开发者的〈重构 UI〉实战笔记:从改好一个设置页开始,告别“程序员审美”
前端·aigc
程序员鱼皮4 小时前
格局!刚刚 DeepSeek 正式开放全家桶 API,咱都能复刻 DeepSeek App 了?
前端·aigc·ai编程
ZhengEnCi4 小时前
登录页电脑端怎么设计才不空:5 种布局方案与可粘贴 AI 提示词
前端·css·设计
Penge6664 小时前
JavaScript:DOM 树
前端