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

动态注册组件

方式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
相关推荐
鳄鱼杆1 分钟前
虚拟机 | 如何通过域名访问虚拟机中的Web服务?
前端
We་ct40 分钟前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
用泥种荷花1 小时前
【LangChain.js学习】 提示词模板
前端
认真的薛薛1 小时前
2-监控:elk采集各种日志并出图
前端·chrome·elk
叶落阁主1 小时前
别再从 0 造后台了:`antdv-next-admin`,开箱即用的 Vue 3 中后台脚手架
前端
yiranlater2 小时前
状态驱动渲染和事件驱动模型
前端
yuki_uix2 小时前
用 useState 管理服务端数据?不如试试 React Query 来“避坑”
前端
薛定e的猫咪2 小时前
Vibe Coding范式实战:用AI工具链(Stitch+Figma+ai studio+Trae)快速开发全栈APP
前端·人工智能·react.js·github·figma
折七2 小时前
2026 年 Node.js 后端技术选型,为什么我选了 Hono 而不是 NestJS
前端·后端·node.js
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Vue的租房App为例,包含答辩的问题和答案
前端·javascript·vue.js