如何对所有三个组件使用动态导入?对于不同的组件,我确实有不同的支持,所以我不能在计算方法中使用switch选项来返回组件。
我确实找到了使用单个组件的解决方案,但从未见过一个示例,其中我可以放置多个将根据条件导入的组件。在UI中,我可以看到我的组件不会因为v-if条件而被加载,但是当我转到Network选项卡并看到JS选项时,我的组件实际上是被导入的。
模板:
<template>
<div>
<b-button v-if="condition1" v-b-toggle.collapse-1 variant="primary">Component1</b-button>
<b-collapse id="collapse-1" class="mt-2">
<b-card>
<p class="card-text">Collapse contents Here</p>
<component :is="condition1" :data1 = "data.cond1" />
</b-card>
</b-collapse>
<b-button v-if="condition2" v-b-toggle.collapse-2 variant="primary">Component2</b-button>
<b-collapse id="collapse-2" class="mt-2">
<b-card>
<p class="card-text">Collapse contents Here</p>
<component :is="condition2" :data2 = "data.cond2" />
</b-card>
</b-collapse>
<b-button v-if="condition3" v-b-toggle.collapse-3 variant="primary">Component3</b-button>
<b-collapse id="collapse-3" class="mt-2">
<b-card>
<p class="card-text">Collapse contents Here</p>
<component :is="condition3" :data3 = "data.cond3" />
</b-card>
</b-collapse>
</div>
</template>
Code:
<script>
export default {
props: {
component: String,
},
data() {
},
computed: {
condition1() {
const condition1 = true; ////this.$store.state.data.cond1.condition1
if(condition1){
return () => import(`../components/component1`);
}
},
condition2() {
const condition2 = false; //this.$store.state.data.cond2.condition2
if(condition2){
return () => import(`../components/component2`);
}
},
condition3() {
const condition3 = true; ////this.$store.state.data.cond3.condition3
if(condition3){
return () => import(`../components/component3`);
}
},
},
created() {
},
},
}
</script>
I tried this and I get an error :
> Unknown custom element:<component> - did you register the component
> correctly? For recursive components, make sure to provide the "name"
> option.
Note: when I try with one condition, it is working fine but going with multiple conditions and components, it is throwing the above error.
Thanks a lot for your answer @power-cut.
As I do have an expandable structure where I need to show the component separately I can't go with just one component approach. 发布于 2022-05-09 19:40:09
在这种情况下,您可能需要重新考虑开发Vue组件的方法。下面是如何基于存储条件实现动态组件。
<template>
<component :is="myDynamicComponent" />
</template>
<script>
import Component1 from './src/component1.vue'
import Component2 from './src/component2.vue'
import Component3 from './src/component3.vue'
export default {
data() {
return {}
},
computed: {
myDynamicComponent() {
switch (this.$store.state.foo) {
case "condition1":
return Component1;
case "condition2":
return Component2;
case "condition3":
return Component3;
default:
return Component1;
}
}
}
</script>https://stackoverflow.com/questions/72176906
复制相似问题