kin*_*sch 6 javascript vue.js vue-component
当我尝试使用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.
Run Code Online (Sandbox Code Playgroud)
不幸的是我不知道是什么导致了这个错误.由于发行说明,我已经尝试在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>
Run Code Online (Sandbox Code Playgroud)
[已解决]
上面的代码有效.问题是基于Loading chunk 0 failed边缘情况.使用webpack设置,output: {publicPath: '/'}它提供相对于根而不是其原点的块.当我在我的外部服务器中嵌入http:// localhost:8080/app.js并从那里调用导入函数时,链接的块URL是http://myserver.com/0.js而不是http:// localhost: 8080/0.js.为了解决这个问题,我必须output: {publicPath: 'http://localhost:8080/'}在webpack配置中进行设置.
根本原因是import()异步(它返回一个Promise),您收到的错误已经告诉您:
[Vue warn]:无法解析异步组件
使用手表会更好,如下面的演示(在内部Promise.then(),更改组件类型),然后挂钩 beforeMount 或 Mounted 以确保 props=type 正确初始化。:
<template>
<div>
<component :is="componentType">
<children/>
</component>
</div>
</template>
<script>
import DefaultComponent from './DefaultComponent'
export default {
name: 'DynamicComponent',
components: {
DefaultComponent
},
props: {
type: String,
},
data: {
componentType: 'DefaultComponent'
},
watch: {
type: function (newValue) {
import(`./types/type-${newValue}`).then(loadedComponent => { this.componentType = loadedComponent} )
}
},
mounted: function () {
import(`./types/type-${this.type}`).then(loadedComponent => { this.componentType = loadedComponent} )
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4377 次 |
| 最近记录: |