首页 文章

动态导入的vue组件无法解析

提问于
浏览
5

当我尝试使用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 回答

  • 1

    根本原因是 import()async (它返回一个 Promise ),你已经告诉过你的错误:

    [Vue警告]:无法解析异步组件

    使用 watch 将更好像下面的demo(Inside Promise.then() ,更改componentType),然后挂钩beforeMount或挂载以确保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>
    

相关问题