当我尝试使用import()函数导入动态组件时,我收到以下错误:
[Vue warn]: Failed to resolve async component: function () {
return __webpack_require__("./src/components/types lazy recursive ^\\.\\/field\\-.*$")("./field-" + _this.type);
}
Reason: Error: Loading chunk 0 failed.
不幸的是我不知道是什么导致了这个错误 . 由于Release Notes,我已经尝试在vue-loader配置中将esModule设置为false .
我使用vue-cli 2.9.2和webpack模板来设置这个项目,这是实际组件的代码:
<template>
<div>
<component :is="fieldType">
<children/>
</component>
</div>
</template>
<script>
export default {
name: 'DynamicComponent',
props: {
type: String,
},
computed: {
fieldType () {
return () => import(`./types/type-${this.type}`)
}
}
}
</script>
[RESOLVED]
上面的代码有效 . 由于边缘情况,该问题基于 Loading chunk 0 failed
. 使用webpack设置 output: {publicPath: '/'}
,它提供相对于根而不是其原点的块 . 当我在我的外部服务器中嵌入http://localhost:8080/app.js并从那里调用导入功能时,链接的块网址是http://myserver.com/0.js而不是http://localhost:8080/0.js . 为了解决这个问题,我必须在webpack配置中设置 output: {publicPath: 'http://localhost:8080/'}
.
1 回答
根本原因是
import()
是 async (它返回一个 Promise ),你已经告诉过你的错误:使用 watch 将更好像下面的demo(Inside
Promise.then()
,更改componentType),然后挂钩beforeMount或挂载以确保props = type正确初始化: