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

动态注册组件

方式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
相关推荐
小磊哥er7 分钟前
【前端工程化】前端工作中的业务规范有哪些
前端
ᥬ 小月亮17 分钟前
webpack基础
前端·webpack
YongGit36 分钟前
探索 AI + MCP 渲染前端 UI
前端·后端·node.js
慧一居士1 小时前
<script setup>中的setup作用以及和不带的区别对比
前端
RainbowSea2 小时前
NVM 切换 Node 版本工具的超详细安装说明
java·前端
读书点滴2 小时前
笨方法学python -练习14
java·前端·python
Mintopia2 小时前
四叉树:二维空间的 “智能分区管理员”
前端·javascript·计算机图形学
Mintopia2 小时前
Three.js 深度冲突:当像素在 Z 轴上玩起 "挤地铁" 游戏
前端·javascript·three.js
Penk是个码农2 小时前
web前端面试-- MVC、MVP、MVVM 架构模式对比
前端·面试·mvc
MrSkye2 小时前
🔥JavaScript 入门必知:代码如何运行、变量提升与 let/const🔥
前端·javascript·面试