主页资讯有三种布局,并且后端返回的数据也不一样,显然页面是组件通过循环子组件来实现的,但是问题来了,每个子组件的的样式和数据是不一样的,可以看到数据中有个type属性,我们可以判断数据中的type值来动态显示组件于是有了下面的代码
//info为父组件循环传给子组件需要在子组件上渲染的数据
<div class="information" v-for="item in informations" :key="item.id">
<Imformation1 v-if="item.type == '1'" :info="item"/>//子组件1
<Imformation2 v-if="item.type == '2'" :info="item"/> //子组件2
<Imformation3 v-if="item.type == '3'" :info="item"/> //子组件3
</div>
但是问题又来了,显然这代码不优雅,如果有很多子组件场景,那么就需要写很多的分支。有没有办法优化呢?
办法总比困难多,想想方法还是有的,因为上面的例子代码比较长,不便于观看,另起一个demo.
普通的解决方法
<Component1 v-if="type==''1" />
<Component2 v-if="type=='2'" />
<Component3 v-if="type=='3'" />
</div>
<template>
<component :is="currentComponent" />
</div>
</template>
<script>
import Component1 from "../components/Component1.vue";
import Component2 from "../components/Component2.vue";
import Component3 from "../components/Component3.vue";
export default {
computed: {
condition: function () {
return this.state.info.type;
currentComponent: function () {
return "Components" + this.condition;
components: {
Component1,
Component2,
Component3,
</script>
这样一来,以后再有新的子组件增加,也仅仅需要引入和注册组件即可,加载的事情就可以自动判断完成了。
本文章主要个人学习时一点心得,如有不妥之初希望各位大佬指出,如果有更好的办法也希望大佬能够提出哦。