基于element封装table、分页

在利用element-ui Table编写项目时,会存在表格展示的数据存在分页的情况,基本每个页面都要配置,很影响开发效率,也不利于后期维护,所以统一封装一下,便于开发使用。
在这里插入图片描述

How to Use:

src/components目录中创建base-table,引用到自己的页面中,可以根据自己的需求自由更改。

base-table组件封装

<template>
  <div class="base-table bg-white">
    <!-- 表格上方操作栏 ,插槽actionBar,配置操作按钮-->
    <div class="table-title flex justify-between align-center">
      <div class="font-sm">{{ tableTitle }}</div>
      <slot name="actionBar"></slot>
    </div>
    <el-table
      :span-method="arraySpanMethod"
      v-loading="loading"
      :element-loading-text="$t('tips.loading')"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      :header-row-class-name="tableHeader"
      :header-cell-style="{ background: '#E3E3E3', color: '#333333' }"
      :row-class-name="tabRowClassName"
      @selection-change="handleCustomSelect"
      ref="table"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="tableData"
      :rowArr="rowSpanArr"
      style="width: 100%"
      :border="border"
    >
      <el-table-column v-if="selection" type="selection" width="55"> </el-table-column>
      <el-table-column v-for="item of labelData" :min-width="item.minWidth" :width="item.width" :label="item.label" :fixed="item.fixed" :align="item.align || 'center'" :key="item.id">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :disabled="!scope.row.showTooltip" v-model="scope.row.showTooltip" :content="scope.row[item.prop]" placement="bottom-start">
            <div @mouseenter="showTips($event, scope.row, scope.index, item.prop)" class="cell-word">{{ scope.row[item.prop] }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <slot></slot>
    </el-table>
    <div class="table-bottom">
      <el-pagination
        v-if="pagi"
        @size-change="handleSelectionChange"
        @current-change="getCurrentPage"
        layout="total, sizes, prev, pager, next"
        :page-sizes="pageSizeArr"
        :page-size="pageSize"
        :current-page.sync="tableCurrentPage"
        :total="counts"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'baseTable',
  props: {
    loading: Boolean,
    tableData: Array,
    labelData: Array,
    rowSpanArr: Array,
    pagi: Boolean,
    counts: Number,
    currentPage: Number,
    selection: Boolean,
    isIndex: Boolean,
    tableTitle: String,
    border: {
      type: Boolean,
      default: true
    },
    merge: {
      type: Boolean,
      default: false
    },
    mergeCells: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      pageSizeArr: [5, 10, 15, 20, 25],
      pageSize: 10,
      tableHeader: 'table-header',
      tableCurrentPage: this.currentPage
    }
  },
  created() {},
  methods: {
    /**
     * @description: 合并行或列的计算方法
     * @param {*} row 当前行
     * @param {*} column 当前列
     * @param {*} rowIndex 当前行号
     * @param {*} columnIndex 当前列号
     */
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.merge) {
        // 只合并区域位置
        if (columnIndex === 0) {
          const _row = this.rowSpanArr[rowIndex]
          return {
            rowspan: _row, // 行
            colspan: 1 // 列
          }
        }
      }
      if (this.mergeCells) {
        // 只合并区域位置
        if (columnIndex === 0) {
          if (rowIndex % this.index === 0) {
            return {
              rowspan: 6,
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      }
      // this.$emit('arraySpanMethod',{ row, column, rowIndex, columnIndex })
    },
    /**
     * @description: 用于多选表格,切换某一行的选中状态,如果使用了第二个参数,则是设置这一行选中与否
     * @param {*} row 当前行
     */
    handleCustomSelect(row) {
     	this.$emit('selection-change', row)
    },
    /**
     * @description: 通过方法计算返回对应class样式
     * @param {*} row 当前行
     * @param {*} rowIndex 当前行号
     * @return {Boolen}
     */
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 === 0) {
        return 'warning-row'
      }
    },
    /**
     * @description: currentPage 改变时会触发
     * @param {*} index 跳转页码
     * @return {*}
     */
    getCurrentPage(index) {
      this.$emit('page-change', index)
    },
    /**
     * @description: pageSize 改变时会触发
     * @param {*} val  每页条数
     * @return {*}
     */
    handleSelectionChange(val) {
      this.$emit('size-change', val)
    },
    showTips(obj, row, index, prop) {
      /* obj为鼠标移入时的事件对象 */
      /* currentWidth 为文本在页面中所占的宽度,创建标签,加入到页面,获取currentWidth ,最后在移除 */
      let TemporaryTag = document.createElement('span')
      TemporaryTag.innerText = row[prop]
      TemporaryTag.className = 'getTextWidth'
      document.querySelector('body').appendChild(TemporaryTag)
      let currentWidth = document.querySelector('.getTextWidth').offsetWidth
      document.querySelector('.getTextWidth').remove()

      /* cellWidth为表格容器的宽度 */
      const cellWidth = obj.target.offsetWidth

      /* 当文本宽度小于||等于容器宽度两倍时,代表文本显示未超过两行 */
      currentWidth <= 2 * cellWidth ? (row.showTooltip = false) : (row.showTooltip = true)
      this.$set(this.tableData, index, row)
      console.log(currentWidth <= 2 * cellWidth ? (row.showTooltip = false) : (row.showTooltip = true))
    }
  },
  mounted() {},
  watch: {
    currentPage() {
      this.tableCurrentPage = this.currentPage
    }
  }
}
</script>

<style lang="scss" scoped>
.base-table {
  border-radius: 4px;
  padding: 16px;
  margin-top: 8px;

  .table-title {
    margin-bottom: 16px;
    color: #4c4c4c;
  }
  .table-bottom {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  /deep/ tr .cell {
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
  }
  .cell-word {
    cursor: pointer;
  }
  /deep/ .warning-row {
    background-color: #f3f3f3;
  }
  /deep/.el-table {
    .cell {
      .el-button {
        margin-bottom: 4px;
        margin-left: 4px;
      }
    }
  }
  .spans {
    margin: 0 6px;
    display: inline-block;
    cursor: pointer;
  }
}
</style>

传参说明

Table Attributes

参数说明类型默认值
tableTitle表格上方标题String-
tableData显示的数据Array-
labelDatatable-column相关配置信息,详见Table-column AttributesArray-
loading区域加载效果,在表格等容器中加载数据时显示。Boolean-
selection是否在表格第一列显示多选框Boolean-
border是否显示表格边框Booleantrue
rowSpanArr合并行或列的数组 [rowIndex/columnIndex]Array-
merge合并行,配合rowSpanArr使用Booleanfalse
mergeCells合并列,配合rowSpanArr使用Booleanfalse
pagi是否显示表格下面的分页Boolean-
counts总条目数Number-
currentPage当前页数,支持 .sync 修饰符Number-

Table Events

事件名说明参数
selection-changetable第一列,多选项发生变化时会触发该事件selection
page-changecurrentPage 改变时会触发当前页
size-changpageSize 改变时会触发每页条数

Table-column Attributes

参数说明类型默认值
label显示的标题String-
prop对应列内容的字段名String-
width对应列的宽度String-
fixed列是否固定在左侧或者右侧,true 表示固定在左侧string, boolean-
align对齐方式Stringcenter

使用模板

需要使用的页面

 // template
 <base-table
   tableTitle="角色列表"
   :label-data="tableData.cloumn"
   :table-data="tableData.data"
   :counts="count"
   pagi
   selection
   :loading="loading"
   @size-change="getSelectionChange"
   :current-page="searchParams.page"
   @page-change="getCurrentPage"
   @selection-change="handleselectione"
 >
   <!-- 表格头部右侧操作栏 -->
   <template slot="actionBar">
     <el-button type="primary">新增角色</el-button>
   </template>
   <!-- 自定义操作列 -->
   <el-table-column align="center" :label="$t('account.actions')">
     <template slot-scope="scope">
       <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
       <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
     </template>
   </el-table-column>
 </base-table>
 
import BaseTable from '@/components/common/baseTable.vue'
// data
export default {
  data() {
    return {
      loading: true,
      tableData: {
        // 表格数据
        data: [],
        cloumn: [
          { label: '角色名称'), prop: 'Name', fixed: true, align: 'left', minWidth: '100px' },
          { label: '角色明细', prop: 'Description', width: '130px' }
        ]
      },
      searchParams: { // 请求参数
        page: 1,
        limit: 10
      },
      count: 234 // 列表总数
    }
  },
  components: { BaseTable },
}
//methods
    // 请求数据
    fetch(){},

    // 下拉框选择每页显示条数
    getSelectionChange(val) {
      this.searchParams.limit = val
      this.searchParams.page = 1
      this.fetch()
    },

    // 切换分页
    getCurrentPage(val) {
      this.searchParams.page = val
      this.fetch()
    },

    // 点击选中当前行
    handleselectione(value) {
      console.log(value)
    },

更多文章__> >> 码砖猿的技术博客

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值