Vue JS动态导入组件 [英] Vue js import components dynamically
问题描述
我有以下父组件,该父组件必须呈现动态子组件的列表:
I have the following parent component which has to render a list of dynamic children components:
<template>
<div>
<div v-for="(componentName, index) in supportedComponents" :key="index">
<component v-bind:is="componentName"></component>
</div>
</div>
</template>
<script>
const Component1 = () => import("/components/Component1.vue");
const Component2 = () => import("/components/Component2.vue");
export default {
name: "parentComponent",
components: {
Component1,
Component2
},
props: {
supportedComponents: {
type: Array,
required: true
}
}
};
</script>
supportedComponents
属性是我要在父组件中呈现的组件名称的列表.
The supportedComponents
property is a list of component names which I want to render in the parent conponent.
为了在父级中使用子级组件,我必须导入它们并注册它们.
In order to use the children components in the parent I have to import them and register them.
但是唯一的方法是对组件的导入路径进行硬编码:
But the only way to do this is to hard code the import paths of the components:
const Component1 = () => import("/components/Component1.vue");
const Component2 = () => import("/components/Component2.vue");
然后像这样注册它们:
components: {
Component1,
Component2
}
我想使我的 parentComponent
尽可能通用.这意味着我必须找到一种方法来避免在导入语句和注册时使用硬编码的组件路径.我想向 parentComponent
中注入应该导入和呈现的子组件.
I want to keep my parentComponent
as generic as possible. This means I have to find a way to avoid hard coded components paths on import statements and registering. I want to inject into the parentComponent
what children components it should import and render.
在Vue中这可能吗?如果是,那怎么办?
Is this possible in Vue? If yes, then how?
推荐答案
您可以在创建的生命周期内加载组件,然后根据您的array属性对其进行注册:
You can load the components inside the created lifecycle and register them according to your array property:
<template>
<div>
<div v-for="(componentName, index) in supportedComponents" :key="index">
<component :is="componentName"></component>
</div>
</div>
</template>
<script>
export default {
name: "parentComponent",
components: {},
props: {
supportedComponents: {
type: Array,
required: true
}
},
created () {
for(let c=0; c<this.supportedComponents.length; c++) {
let componentName = this.supportedComponents[c];
this.$options.components[componentName] = () => import('./' + componentName + '.vue');
}
}
};
</script>
效果很好
这篇关于Vue JS动态导入组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!