当我try 使用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.

不幸的是,我不知道是什么导致了这个错误.我已经try 在vue加载程序配置中将esModule设置为false,原因是Release Notes.

我使用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]
The code above works. The issue was based on the Loading chunk 0 failed due to an edge case. With webpack setting output: {publicPath: '/'} it delivers the chunks relative to the root instead of its origin. When I embed the http://localhost:8080/app.js in my external server and called from there the import function the linked chunk url was http://myserver.com/0.js instead of http://localhost:8080/0.js. To fixed this I had to set output: {publicPath: 'http://localhost:8080/'} in the webpack configuration.

推荐答案

根本原因是import()async(返回Promise),错误已经告诉您:

[warn Vue]:解析异步组件失败

使用watch将更好地像下面的演示(在Promise.then()内,更改组件类型),然后在安装或安装前挂钩,以确保正确初始化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>

Vue.js相关问答推荐

Vue3多姆参考已安装的添加EventButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButtButt

Vue CDN的html工作,但v—如果不工作

Vue3外部数组的响应性

Shopware 6,使用 vue-test-utils 进行Jest 测试:渲染模板上的意外行为

如何在 vue 组件中定义变量? (Vue.JS 2)

Vuejs中的条件a href

Vue:限制文本区域输入中的字符,截断过滤器?

如何将 axios/axios 拦截器全局附加到 Nuxt?

React.js 是否有类似 Vue.js

等待来自 WDS 的更新信号

使用 Vue.js 的用户可切换自定义主题

为 webpack HMR Vue.js 包含来自外部项目文件夹的可导入模块

触发子函数

Vue CLI 3 sass-resources-loader - Options.loaders 未定义

laravel vuejs/axios put request Formdata 为空

Vue.js 3 - 替换/更新react性对象而不会失go react性

Vue $refs 对象的类型为 unknown未知

表格行上的 Vuejs 转换

在 Vuex 模块中进行继承的方法

在~/components/AddPlaceModal.vue中找不到导出AddPlaceModal