vue-elementUI-table-自定义表头和行合并

6次阅读

共计 1801 个字符,预计需要花费 5 分钟才能阅读完成。

最近项目中做表格比较多,对 element 表格的使用,只需要传递进去数据,然后写死表头即可渲染。

但现实中应用中,如果写死表头,并且每个组件中写自己的表格,不仅浪费时间而且消耗性能。这个时候需要动态渲染表头。

而官方例子都是写死表头,那么为了满足项目需求,只能自己来研究一下。

1、自定义表头

代码如下,其实就是分了两部分,表格主数据是在 TableData 对象中,表头的数据保存在 headerDatas,headerDatas.label 其实就是表头的值,如果表头是“序号”,那么 headerDatas.label=” 序号 ”,在 TableData 中构建 TableData[序号]= 1 这样的 map 对象,就可以动态渲染出想要的表格


<el-table
          :data="TableData"
          :height="tableHeight"
          :row-class-name="showEmergencyLine"
          border
          element-loading-spinner="el-icon-loading"
          element-loading-text="拼命加载中"
          @selection-change="handleSelectionChange"
          v-loading.lock="TableLoading"
          @header-dragend="changeHeaderWidth"
        >
         <el-table-column
            v-for="header in headerDatas"
            :prop="header.type"
            :key="header.label"
            :label="header.label"
            :width="header.width"
            :minWidth="header.minWidth"
            :itemname="header.mid"
            :align="header.align"
            header-align="center"
          >
          <template slot-scope="scope">
          <div
            v-else
          >{{scope.row[scope.column.property]}}</div>
          </template>
          </el-table-column>
</el-table>

2、行合并

在项目中,有些表格常常会有像下面这样的需求,一行合并后面几行,那么这个怎么处理呢

官方文档中有这个方法

通过给 table 传入 span-method 方法可以实现合并行或列,方法的参数是一个对象,里面包含当前行 row、当前列 column、当前行号 rowIndex、当前列号 columnIndex 四个属性。该函数可以返回一个包含两个元素的数组,第一个元素代表 rowspan,第二个元素代表 colspan。也可以返回一个键名为 rowspan 和 colspan 的对象。

<el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      highlight-current-row
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      v-loading.lock="mainTableLoading"
      border
      style="width: 100%; margin-top: 25px"
    >
</el-table>

    arraySpanMethod({row, column, rowIndex, columnIndex}) {if (rowIndex % 2 === 0) {// 偶数行
          if (columnIndex === 0) {// 第一列
            return [1, 2];// 1 合并一行,2 占两行
          } else if (columnIndex === 1) {// 第二列
            return [0, 0];// 0 合并 0 行,0 占 0 行
          }
        }
      },

      objectSpanMethod({row, column, rowIndex, columnIndex}) {if (columnIndex === 0) {if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,// 合并的行数
              colspan: 1// 合并的列数,设为0则直接不显示
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }

这里面可以通过对 rowIndex,columnIndex 根据自己的要求作一些条件判断,然后返回 rowspan,colspan 就可以合并了。

正文完
 0