Vue2实现动态组件

使用场景:同一个区域因状态不同或者tab页,展示给用户不同模版样式逻辑的组件

动态组件实现,是通过使用 is attribute 来切换不同的组件

<component v-bind:is="currentTabComponent"></component>

 ​​​​​​

 一、公共动态组件父组件(可以通过keep-alive缓存)

<!-- 公共动态组件 isComponent.vue -->
<template>
  <div>
    <el-button :class="currentClass(item)" v-for="item in Object.keys(Dict)" :key="item" @click="changeBtn(item)">
      {{ item }}
    </el-button>
    <div>
      <keep-alive>
        <!-- 根据component搭配is内容进行动态切换显示内容 -->
        <component :is="currentTabComponent" :data="data" ref="comp"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
// 引入动态显示的组件
import compA from './components/dynamicComponents/compA.vue'
import compB from './components/dynamicComponents/compB.vue'

export default {
  name: "myTabsName",
  components: { compA, compB },
  data() {
    return {
      currentTabComponent: 'compA',
      data: '西游记',
      // 自定义字典
      Dict: {
        '西游记': 'compA',
        '水浒传': 'compB',
      }
    };
  },
  computed: {
    // 通过计算属性添加class类
    currentClass() {
      return (item) => {
        if (this.currentTabComponent === this.Dict[item]) { return 'active' }
      }
    }
  },
  methods: {
    // 切换tab事件
    changeBtn(val) {
      this.currentTabComponent = this.Dict[val]
      this.data = val
    }
  },
};
</script>

<style lang="scss" scoped>
.active {
  background-color: red;
  color: white;
}
</style>

 二、1.公共动态组件子组件A

<!-- 公共动态子组件 compA.vue -->
<template>
  <div class="aa">
    {{ data }}
    <br>
    <el-input class="inp" v-model="formA"></el-input>
  </div>
</template>

<script>
export default {
  name: "compA",
  props: {
    data: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formA: ''
    }
  }
};
</script>
<style>
.aa {
  background-color: rgb(250, 203, 211);
  margin: 10px auto;
  width: 500px;
  height: 300px;
}

.inp {
  width: 100px;
}
</style>

   二、2.公共动态组件子组件B

<!-- 公共动态子组件 compB.vue -->
<template>
  <div class="bb">
    {{ data }}
  </div>
</template>

<script>
export default {
  name: "compB",
  props: {
    data: {
      type: String,
      default: ''
    }
  },
};
</script>

<style>
.bb {
  background-color: rgb(181, 200, 244);
  margin: 10px auto;
  width: 500px;
  height: 300px;
}
</style>

 做个记录,如有不足,欢迎补充。

 不要忽视你达成的每个小目标,它是你前进路上的垫脚石。冲!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值