我有很多组件,我想按需导入。我有一个下拉菜单,其中实际上包含要加载的组件列表。我试过这个例子
<component :is="componentLoader"></component>
Run Code Online (Sandbox Code Playgroud)
在脚本中
componentLoader () {
return () => import('@/components/testDynamic')
}
Run Code Online (Sandbox Code Playgroud)
testDynamic是一个组件名称(目前我正在尝试使用静态组件)。
得到这个错误
GET http://localhost:8080/0.js net::ERR_ABORTED 404
[Vue warn]: Failed to resolve async component: function () {
return __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, "./src/components/testDynamic.vue"));
}
Reason: Error: Loading chunk 0 failed.
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?我做错什么了吗?还是有其他方法可以动态导入组件?
Rak*_*ora 14
我遇到了同样的问题,因为我使用的是 Vue 3,这里给出的解决方案都不适合我。经过一番研究,我发现在 Vue 3 中定义动态组件(异步组件)的过程有点不同。我希望这段代码对某人有所帮助。
<template>
<component :is="comp"></component>
</template>
<script>
//Vue 3 is having a special function to define these async functions
import {defineAsyncComponent} from "vue";
export default {
name: "DynamicComponent",
//I am passing the name of the Component as a prop
props: {
componentName:{
type: String,
required: true
}
},
computed: {
comp () {
return defineAsyncComponent(() => import(`@/components/${this.componentName}.vue`))
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
您可以在单个文件组件中本地注册异步动态组件,如下所示:
export default {
components: {
'test-dynamic': () => import('@/components/testDynamic'),
'other-dynamic': () => import('@/components/otherDynamic')
},
data () {
return {
current: 'test-dynamic'
}
}
}
Run Code Online (Sandbox Code Playgroud)
在您的模板中:
<component :is="current"></component>
Run Code Online (Sandbox Code Playgroud)
如果您注册了多个组件,则只需将的值更改current为所需的组件。
对于许多组件,您可以导入一个将组件名称映射到其各自文件路径的对象,然后按以下方式注册它们:
import myComponents from '@/components'
export default {
components: Object.keys(myComponents).reduce((obj, name) => {
return Object.assign(obj, { [name]: () => import(myComponents[name]) })
}, {})
...
}
Run Code Online (Sandbox Code Playgroud)
哪里myComponents导出为:
// components/index.js
export default {
foo: '@/path/to/Foo',
bar: '@/path/to/Bar',
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4048 次 |
| 最近记录: |