超好用的element的el-table表格组件二次封装-附源码及讲解

前言:在很多后台管理系统开发时总会有很多表格的使用,如果我们每次都用elementui官网的el-table去写的话,调整所有表格的样式就会很麻烦,而且页面内容也会很累赘繁琐。

讲解一个我经常使用的二次封装el-table组件,该组件可以容纳很多种特定的需求并且非常简便。所有例子都是使用vue2+elementUI,如要使用vue3稍作修改即可,也可评论问我

直接上代码:

一、组件代码

<template>
  <el-table
    ref="multipleTable"
    v-loading="tableLoading"
    :data="tableData"
    element-loading-text="拼命加载中"
    :height="height"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(20, 60, 133, 0.8)"
    tooltip-effect="dark"
    style="width: 100%; "
    border
    :row-class-name="rowClassName"
    :header-cell-style="{ background: '#0e3372', color: '#cccccc' }"
    stripe
    @selection-change="handleSelectionChange"
  >
    <template v-if="isSelection">
      <el-table-column type="selection" width="55" />
    </template>

    <template v-for="(item,index) in column">
      <el-table-column
        :key="index"
        :label="item.label"
        :prop="item.prop"
        :type="item.type"
        :width="item.width"
        :fixed="item.fixed"
        :sortable="item.sortable?true:false"
        :filters="item.filters"
        :column-key="item.columnKey"
        :filtered-value="item.filteredValue"
        :filter-multiple="item.filterMultiple"
        :min-width="item.minWidth"
        align="center"
      >

        <!-- <div class="123" v-if="item.type == ''"> -->
        <template v-if="item.hasOwnProperty('colunmTemplate')" :slot="item.colunmTemplate" slot-scope="scope">
          <slot v-if="item.theadSlot" :name="item.theadSlot" :row="scope.row" :index="index" />
        </template>

        <template slot-scope="scope">
          <!-- 插槽 -->
          <div v-if="item.dataType == 'slot'">
            <slot v-if="item.slot" :name="item.slot" :row="scope.row" :index="scope.$index" />
          </div>


          <!-- 进度条 -->
          <div v-else-if="item.dataType == 'progress'">
            <el-progress :percentage="Number(scope.row[item.prop])" />
          </div>

          <!-- tag -->
          <div v-else-if="item.dataType == 'tag'">

            <el-tag v-if="typeof dataTypeFn(scope.row[item.prop],item.formatData) == 'string'" :title="scope.row[item.prop] | formatters(item.formatData)" :type="formatType(scope.row[item.prop],item.formatType)">
              {
   
   { scope.row[item.prop] | formatters(item.formatData) }}
            </el-tag>

            <el-tag v-for="(tag,index) in dataTypeFn(scope.row[item.prop],item.formatData)" v-else-if="typeof dataTypeFn(scope.row[item.prop],item.formatData) == 'object'" :key="index" :title="scope.row[item.prop] | formatters(item.formatData)" :type="formatType(tag,item.formatType)">
              {
   
   { item.tagGroup ? tag[item.tagGroup.label]?tag[item.tagGroup.label]:tag : tag }}
            </el-tag>

            <el-tag v-else :title="scope.row[item.prop] | formatters(item.formatData)" :type="formatType(scope.row[item.prop],item.formatType)">
              {
   
   { scope.row[item.prop] | formatters(item.formatData) }}
            </el-tag>

          </div>

          <!-- 按钮 -->
          <div v-else-if="item.dataType == 'option'">
            <el-button
              v-for="(o, key) in item.operation"
              v-show="o.showHide?o.showHide(scope.row):true"
              :key="key"
              :icon="o.icon | iconFn(scope.row)"
              :disabled="o.disabled?o.disabled(scope.row):false"
              :plain="o.plain"
              :type="o.type | typeFn(scope.row)"
              :size="o.size"
              @click="o.clickFun(scope.row)"
            >
              {
   
   { o.name }}
                  </el-button>
          </div>

          <!--  -->

          <!-- 默认纯展示数据 -->
          <div v-else>
            <span v-if="!item.formatData">{
   
   { scope.row[item.prop] }}</span>
            <span v-else>{
   
   { scope.row[item.prop] | formatters(item.formatData) }}</span>
          </div>

        </template>

        <!-- </div>   -->

      </el-table-column>
    </template>

  </el-table>
</template>

<script>
export default {
  filters: {
    iconFn(val, row) {
      if (typeof (val) === 'function') {
        return val(row)
      } else return val
    },
    typeFn(val, row) {
      console.log(val,row,'11111111');
      if (typeof (val) === 'function') {
        return val(row)
      } else return val
    },
    describeConts(val, describeCont) {
      if (typeof (describeCont) === 'function') {
        return describeCont(val)
      } else return val
    },
    formatters(val, format) {
      if (typeof (format) === 'function') {
        return format(val)
      } else return val
    }
  },
  props: {
    isSelection: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: null
    },
    tableLoading: {
      type: Boolean,
      default: false
    },
    handleSelectionChange: {
      type: Function,
      default: () => {
        return () => {}
      }
    },
    headerCellStyle: {
      type: Object,
      default: () => {
        return {}
      }
    },
    column: {
      type: Array,
      default() {
        return [
        ]
      }
    },
    rowClassName: {
      type: Function,
      default: () => {

      }
    },
    tableData: {
      type: Array,
      default() {
        return []
      }
    }
  },

  methods: {
    formatType(val, format) {
      if (typeof (format) === 'function') {
        return format(val)
      } else return ''
    },
    dataTypeFn(val, format) {
      if (typeof (format) === 'function') {
        return format(val)
      } else return val
    }
  }
}
</script>

<style scoped>
span{
  white-space: pre-wrap;
}
  /* .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  } */

/* .app-container /deep/  .el-table, .el-table__expanded-cell {
  background-color: transparent;
}

.app-container /deep/ .el-table tr {
  background-color: transparent!important;
}
.app-container /deep/  .el-table--enable-row-transition .el-table__body td, .el-table .cell{
  background-color: transparent;
} */
</style>

 组件里面的细节就不一一细说了,如果想了解怎么写的,仔细看一遍的话其实就会知道该传什么参数怎么用了。但是如果初学者对父子传参还不熟练,想快速使用该组件的话就继续往下看吧

二、如何使用该组件

1、先导入该组件
import TableCom from '@/components/Table/index'

  在compnents中别忘了注册一下你导入进来的TableCom

  components: { TableCom},
2、然后在html中如下图写入组件
<TableCom
        :column="columnData"
        :table-data="tableData"
        :table-loading="tableLoading"
      >
</TableCom>

注:

column:每一列的配置项(列名、大小、插槽等等),类型:数组Arrary

tabledata:表格的数据(一般就是后端传过来的数组,数组里面是对象),类型:数组Arrary

tableLoading:加载过程显示,类型:布尔值boolean

headerCellStyle:表头颜色设置,类型:对象Object

3、columnData举例数据:
(这里就会渲染出一个四列的表格,每一列分别是名称、启用状态、协议、操作)
columnData: [
        {
          type: '',
          label: '名称',
          prop: 'name'
        },
        {
          type: '',
          label: '启用状态',
          prop: 'is_active',
          formatData: (item) => {
            const str = item == true ? '已启用' : '未启用'
            return str
          }
        },
        {
          type: '',
          label: '协议',
          prop: 'protocol',
          dataType: 'slot',
          slot: 'protocolSlot'
        },
        {
          dataType: 'option',
          label: '操作',
          width: '300px',
          operation: [
            {
              name: '编辑',
              type: '',
              size: 'mini',
              icon: 'el-icon-edit',
              plain: true,
              showHide: (row) => {
              },
              clickFun: (row) => {
              }
            },
            {
              name: '删除',
              type: 'danger',
              size: 'mini',
              showHide: (row) => {
              },
              icon: 'el-icon-delete',
              plain: true,
              clickFun: (row) => {
              }
            }

          ]

        }
      ],

//表格数据
tableData: [{name:111,is_active:true,protocol:'TCP'},
{name:111,is_active:true,protocol:'TCP'},
{name:111,is_active:true,protocol:'TCP'}],

注:以下是所有配置项,其中最常使用的就是label、width、prop、dataType、slot

  1.  label :列名,就是表头上的标签叫什么些什么,类型 string
  2. width:该列宽度, string
  3.  prop:  table绑定数据字段 string,这一列要展示哪个tableData里面的字段就写哪个字段
  4. dataType:  内置多个基本的element组件可供直接使用 string
  5. slot  当`dataType`为`slot`时必带参数,参数值为插槽的 `slot` 值 string,具体使用方法请看下面的第4点slot插槽的使用
  6. fixed:列是否固定在左侧或者右侧,true 表示固定在左侧 string, boolean
  7. sortable 对应列是否可以排序 boolean, string
  8.  filters 数据过滤的选项,数组格式,数组中的元素需要有 text 和 value 属性。Array
  9. columnKey :column 的 key,如果需要使用 filter-change 事件,则需要此属性标识是哪个 column 的筛选条件
  10.  filteredValue  选中的数据过滤项,如果需要自定义表头过滤的渲染方式,可能会需要此属性。
  11.  filterMultiple  数据过滤的选项是否多选
  12.  minWidth 对应列的最小宽度,与 width 的区别是 width 是固定的,min-width 会把剩余宽度按比例分配给设置了 min-width 的列 string
  13.  formatData  对数据进行数据处理,接受一个回调函数 (params?: {prop}) => {}
  14.  formatType  当 `dataType`为 `tag`时,对标签颜色设置 (params?: {prop}) => { return 'danger'| 'success'... }`
  15. operation 当 `dataType` 为 `option`时,对按钮的 配置,具体配置项以下图为准object
  16.  tagGroup 当 `dataType`为 `tag`时,绑定数据集字段显示名称 object
4、如何使用插槽

比如我们刚刚举例子的协议这一列,我们的需求可能不只是单单只展示一个协议,想设计成tag的样式,那么我们就需要用到插槽,如下图,要将dataType设为‘slot’,然后slot设为自己想取的插槽名称都可以,这个名称是要拿去html里用的

然后我们在html里的原本的组件里面加入插槽的内容:

<TableCom
        :column="columnData"
        :table-data="tableData"
        :table-loading="tableLoading"
      >
 <div
     slot="protocolSlot"
     slot-scope="scope"
    >
        <el-tag>{
   
   {scope.row.protocol}}</el-tag>
</div>
</TableCom>

 注:这里div的slot就是你在column里刚刚取得slot名称,然后在里面就可以任意编写样式或者直接使用elementUI里面的组件,想要使用数据时就可以用scope.row.XXX,这里还是要展示协议那个字段,所以就使用了protocol,与前面举例数据tableData里的字段相对应。

5、使用formatData进行数据处理

如下我们刚刚举例数据里面的:

 {
          type: '',
          label: '启用状态',
          prop: 'is_active',
          formatData: (item) => {
            const str = item == true ? '已启用' : '未启用'
            return str
          }
        },

这里主要是用于后端传给我们的数据我们不是直接展示的,需要根据数据发生变化,比如tableDate里面的is_active里面的是true和false,但是要展示的是已启用和未启用,就需要用到formData

6、dataType里面可以使用的其他参数

除了前面第四点说的插槽用slot,还可以用tag(标签项)、progress(进度条)、option(按钮配置项),tag和progress进度条可以自己试试

7、operation配置

operation配置主要是来用于表格里面的操作那一列,通常就会有很多按钮,有以下参数:

name:按钮名称,string

type:按钮类型,`string` | `danger | success`,以elementUi 参数为准

size:按钮大小,以elementUi 参数为准

icon:按钮上的icon,以elementUi 参数为准

plain:按elementUi 文档为准

clickFun:按钮的回调函数

猜你喜欢

转载自blog.csdn.net/wzy_PROTEIN/article/details/134048267