xuanweiH / Project-issue

记录项目遇到一些问题与封装
2 stars 0 forks source link

简单表格封装组件 #4

Open xuanweiH opened 4 years ago

xuanweiH commented 4 years ago

如果是在做一些后台管理同学,经常会写表格 而大多情况下的表格比较简单, 就是普通的el-table + el-table-column 为了避免写太多的重复代码.可以稍加进行封装

<template>
  <el-table :data="data" v-on="$listeners" v-bind="$attrs" class="c-simple-table">
    <el-table-column
      v-if="selectionColumn"
      type="selection"
    >
    </el-table-column>
    <el-table-column
      v-if="showIndex"
      type="index"
      width="50"
      label="序号"
    >
    </el-table-column>
    <el-table-column v-bind="head.props" v-on="head.on" :key="index" v-for="(head, index) in headData"
      :label="head.label"
      :prop="head.prop"
      :min-width="head.width"
      :align="head.align || 'left'"
      :sortable="head.sortable"
    >
      <template slot-scope="scope">
        <template v-if="!$scopedSlots[head.prop]" class="cell-content">{{scope.row[head.prop] !== '' ? scope.row[head.prop] : '--'}}</template>
        <slot v-else :name="head.prop" v-bind="scope"></slot>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  name: 'simple-table',
  data () {
    return {
    }
  },
  props: {
    data: Array,
    headData: Array,
    showIndex: {
      type: Boolean,
      default: false
    },
    selectionColumn: {
      type: Boolean,
      default: false
    }
  }
}
</script>

封装的思路也非常简单, 通过两个字段来控制是否需要selectiomColumn勾选框以及序号showIndex 对于表头数据传递一个数组headData来进行循环渲染.表格内容给一个插槽

这样可以通过配置headData数据 headData: [ { label: '已关联品类', prop: 'name', width: '60%', align: 'center' }, { label: '已关联商品数量', prop: 'count', width: '20%', align: 'center' }, { label: '操作', prop: 'operation', width: '20%', align: 'center' } ],