vue element-ui动态渲染多级table表头

效果

1601016549766.jpg

将el-table和el-table-column独立出来
el-table封装如下:
MyTable.vue

<template>
  <div class="my-table">
    <el-table :data="data">
      <my-column v-for="(item,index) in col" :key="index" :col="item"></my-column>
    </el-table>
  </div>
</template>

<script>
import MyColumn from './MyColumn'
export default {
  components: {
    MyColumn
  },
  props: {
    col: {
      type: Array
    },
    data: {
      type: Array
    }
  }
}
</script>
<style scoped>
</style>

el-table-column封装如下:
MyColumn.vue

<template>
  <el-table-column
    :prop="col.prop"
    :label="col.label"
    align="left">
    <template v-if="col.children && col.children.length">
      <my-column v-for="(item, index) in col.children"
        :key="index"
        :col="item"></my-column>
    </template>
  </el-table-column>
</template>

<script>
export default {
  name: 'MyColumn',
  props: {
    col: {
      type: Object
    }
  }
}
</script>
<style scoped>
</style>

使用

<template>
  <div class="my-table">
    <my-table  v-if="tableShow" :col="col" :data="data"></my-table>
  </div>
</template>

<script>
import MyTable from '../components/MyTable'
import { getBt } from '../common/api/system_userApi'
export default {
  components: {
    MyTable
  },
  data() {
    return {
      tableShow:true,// 使组件重新渲染变量
      col: [
        {
          prop: 'date',
          label: '日期'
        },
        {
          label: '配送信息',
          children: [
            {
              prop: 'name',
              label: '姓名'
            },
            {
              label: '地址',
              children: [
                {
                  prop: 'province',
                  label: '省份',
                },
                {
                  prop: 'city',
                  label: '市区'
                },
                {
                  prop: 'address',
                  label: '地址'
                }
              ]
            }
          ]
        }
      ],
      data: [
        {
          date: '2016-05-03',
          name: '王小虎',
          province: '上海',
          city: '普陀区',
          address: '上海市普陀区金沙江路 1518 弄',
          zip: 200333
        },
        {
          date: '2016-05-02',
          name: '王小虎',
          province: '上海',
          city: '普陀区',
          address: '上海市普陀区金沙江路 1518 弄',
          zip: 200333
        }
      ]
    }
  },
  created() {
    this.init();
  },
  methods:{
    //调接口从后台获取表头数据
    init(){
        getBt({}).then(res => {
          this.tableShow = false// 设置tableShow为false,使组件重新渲染
          this.col=res.tbCsBts
          this.$nextTick(() => {// DOM 更新了
            this.tableShow = true
          })
        });
    }
  }
}
</script>
<style scoped>
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。