动态组件使用

36 阅读1分钟
<template>
    <div>
       //豆腐块组件
       <Top 
       v-for="(t, i) in tabs" 
       v-bind="t.props" 
       :key="i"   
       @click.native="handleTopCellClick(t)"
       :class="{active: currentTab.comp === t.comp}" 
       />
       //动态
       <component :is="currentTab.comp"/>  
    </div>
</template>

<script lang="jsx">
import TOP from 'TOP.vue'
import A from 'A.vue'
import B from 'B.vue'
import C from 'C.vue'

export default {
  components: { TOP },
  data() {
    return {
      currentTab: {},
      data: {},
    }
  },
  computed: {
    tabs() {
      const data = this.data
      return [
        {
          comp: {
            render() {
              return <A />
            }
          },
          props: {
            name: 'A',
            title: 'AAA',
            value: <span>11111</span>,
            metrics: [
              {
                title: '目标',
                value: '111'
              },
              {
                title: '达成',
                value: '11.11%
              },
            ]
          }
        },
        {
          comp: {
            render() {
              return <B />
            }
          },
          props: {
            name: 'B',
            title: 'BBB',
            value: <span>22222</span>,
            metrics: [
              {
                title: '目标',
                value: '2222'
              },
            ]
          }
        },
        {
          comp: {
            render() {
              return <C/>
            }
          },
          props: {
            name: 'C',
            title: <span>CCC<span style='xxx....'>(cccc)</span></span> ,
            value: <span>33333</span>,
            metrics: [
              {
                title: '目标',
                value: '3333'
              },
            ]
          }
        },
      ]
    }
  },
  created() {
    this.currentTab = this.tabs[0]
    this.getData()
  },
  methods: {
    async getData() {
      const res = await //获取接口数据
      this.data = res.data?.[0] || {}
    },
    handleTopCellClick(t) {
      if(t.comp) {
        this.currentTab = t
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  xxx...
</style>