gpt4 book ai didi

javascript - 动态导入vue组件解析失败

转载 作者:数据小太阳 更新时间:2023-10-29 05:34:47 25 4
gpt4 key购买 nike

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


[已解决]
上面的代码有效。该问题是基于 Loading chunk 0 failed due to edge case。使用 webpack 设置 output: {publicPath: '/'} 它提供相对于根而不是其来源的 block 。当我嵌入 http://localhost:8080/app.js在我的外部服务器中并从那里调用导入函数链接的 block url 是 http://myserver.com/0.js而不是 http://localhost:8080/0.js .为了解决这个问题,我必须在 webpack 配置中设置 output: {publicPath: 'http://localhost:8080/'}

最佳答案

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

[Vue warn]: Failed to resolve async component

使用 watch 会更好,就像下面的演示(在 Promise.then() 中,更改 componentType),然后 Hook 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>

关于javascript - 动态导入vue组件解析失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com