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

动态注册组件

方式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
相关推荐
一枚前端小能手6 分钟前
「周更第3期」实用JS库推荐:Lodash
前端·javascript
艾小码6 分钟前
Vue组件到底怎么定义?全局注册和局部注册,我踩过的坑你别再踩了!
前端·javascript·vue.js
Cyan_RA913 分钟前
计算机网络面试题 — TCP连接如何确保可靠性?
前端·后端·面试
谢尔登13 分钟前
【CSS】层叠上下文和z-index
前端·css
鹏多多14 分钟前
前端复制功能的高效解决方案:copy-to-clipboard详解
前端·javascript
AryaNimbus16 分钟前
你不知道的 Cursor系列(三):再也不用死记硬背 Linux 命令,终端 Cmd+K 来帮你!
前端·ai编程·cursor
uhakadotcom18 分钟前
Rollup 从0到1:TypeScript打包完全指南
前端·javascript·面试
Mintopia23 分钟前
实时语音转写 + AIGC:Web 端智能交互的技术链路
前端·javascript·aigc
2503_9284115625 分钟前
9.15 ES6-变量-常量-块级作用域-解构赋值-箭头函数
前端·javascript·es6
Pedantic27 分钟前
SwiftUI ShareLink – 显示分享表单的使用
前端