簡體   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