小郭哥
小郭哥
  • 发布:2023-01-08 12:19
  • 更新:2023-01-08 22:43
  • 阅读:297

异步加载组件时,加载组件路径为变量,加载失败

分类:uni-app

一、问题描述
异步加载组件时,加载组件路径为字符串时,加载成功,路径为变量时,加载失败

二、代码
1.template代码

<view v-for="(item,index) in arrComponent" :key="item.id" style="height: 100px">  
    <view> 加载第{{ item.id }}个组件</view>  
    <component v-bind:is="item.comp"></component>  
</view> 

2.js代码

// 加载组件路径为字符串 【成功】  
this.arrComponent.push({  
    id: 1,  
    comp: () => import('./widget/son1.vue')  
})  
//加载组件路径为变量 【失败】  
let compName2 = './widget/son2.vue'  
this.arrComponent.push({  
    id: 2,  
    comp: () => import(compName2)  
})

三、显示报错:
chunk-vendors.js:2765 [Vue warn]: Failed to resolve async component: function comp() {
return Promise.resolve("".concat(compName2)).then(function (s) {
return (0, _interopRequireWildcard2.default)(__webpack_require__("JBzs")(s));
});
}
Reason: Error: Cannot find module './widget/son2.vue'
四、报错截图
报错截图

2023-01-08 12:19 负责人:无 分享
已邀请:
呆狗的一生

呆狗的一生 - 呆狗的一生

具体原因我也不知道,你可以改成以下这样。另外,微信小程序不支持 component这样的动态组件,还是换一种方式吧!

<script>  
    import comp1 from './widget/son1.vue'  
    import comp2 from './widget/son2.vue'  
    export default {  
        data() {  
            return {  
                arrComponent: []  
            }  
        },  
        components: {  
            comp1,  
            comp2  
        },  

        onLoad() {  
            this.arrComponent.push(  
            { id: 1, comp: 'comp1' },  
            { id: 2, comp: 'comp2' }  
        )}  

    }  
</script>

要回复问题请先登录注册