繁体   English   中英

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

[英]Dynamic imported vue component failed to resolve

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

不幸的是我不知道是什么导致了这个错误。 由于发行说明,我已经尝试在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>


[解决]
上面的代码有效。 问题是由于边缘情况导致Loading chunk 0 failed 使用webpack设置output: {publicPath: '/'}它提供相对于根而不是其原点的块。 当我在我的外部服务器中嵌入http:// localhost:8080 / app.js并从那里调用导入函数时,链接的块URL是http://myserver.com/0.js而不是http:// localhost: 8080 / 0.js。 为了解决这个问题,我必须在webpack配置中设置output: {publicPath: 'http://localhost:8080/'}

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

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

使用手表会更好像下面的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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM