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

动态注册组件

方式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
相关推荐
0思必得07 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice7 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3607 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额8 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a10 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌4110 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡11 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone11 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_090111 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农11 小时前
Vue 2.3
前端·javascript·vue.js