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

动态注册组件

方式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
相关推荐
kyriewen13 分钟前
我看完这篇安全论文——AI推荐的npm包,92%是编出来的
前端·javascript·ai编程
小心我捶你啊2 小时前
数据采集和Web解锁不是一回事,从用途到规则区分
前端·爬虫·网络协议
hunterandroid2 小时前
[鸿蒙从零到一] ArkUI 基础组件实战:Text、Image、Button 与 TextInput
前端
fsssb2 小时前
Chromium 源码学习笔记(五):一次点击,在进入 JS 之前先经历了什么?
前端
hunterandroid2 小时前
WorkManager 可靠性实战:唯一任务、重试与幂等设计
android·前端
鹿目2 小时前
使用 Vant CLI 搭建 UI 组件库:从 H5 到小程序跨平台
前端·javascript
默_笙2 小时前
😭 我花了两小时找了一个数据结构 bug,才把"迷你 Cursor"跑起来,绝望(bushi)
前端·javascript
竹林8183 小时前
wagmi v2 监听合约事件踩坑记:从 `useContractEvent` 到 `watchContractEvent`,我重构了三版才搞定实时数据流
前端·javascript
天若有情6733 小时前
纯HTML+Tailwind单页作品集网站——零框架静态前端完整源码
前端·html