表格组件二次封装(element+vue)

后端管理系统中,常用表格展示数据,统一维护,统一表格风格,二次封装一个基于elementUI中的el-table封装一个简单的表格组件。封装组件分为四部分,表单查询条件、头部操作按钮、表格数据展示、数据分页操作。

一、表格组件封装 

1、表单查询条件 

 封装表单项,定义name、label,表单项默认为输入框,scopedSlots为表单项插槽。

// 表单项
queryForms: [{
 dataKey: 'nickName',
 label: `用户昵称`
},
{
 dataKey: 'status',
 label: `状态`,
 scopedSlots: 'query-status'
}],
// 查询参数
queryParams: {
 nickName:"",
 status:"",
 pageNum: 1,
 pageSize: 10,
},
<!-- 表格组件 -->
    <!-- @submit.native.prevent 阻止表单的默认提交行为 -->
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="medium" :inline="true"
      v-show="isShowSearch" :label-width="lableWidth">
      <!--表格头部筛选条件   -->
      <template v-for="(form, index) in queryForms">
        <!-- 表单插槽 -->
        <el-form-item v-if="form.scopedSlots" :label="form.label" :key="index + 'query'"  :prop="form.dataKey">
          <slot :scope="{ queryParams, form, handleQuery }" :name="form.scopedSlots"></slot>
        </el-form-item>
        <!-- 输入框筛选 -->
        <el-form-item v-else :label="form.label"  :key="index + 'query-key'" :prop="form.dataKey">
          <el-input v-model="queryParams[form.dataKey]" :placeholder="'请输入' + form.label" clearable
            @keyup.enter.native="handleQuery" @clear="handleQuery" style="width: 180px" />
        </el-form-item>
      </template>
      <!-- 表格筛选条件操作按钮   -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
        <slot name="export"></slot>
      </el-form-item>
    </el-form>

2、 头部操作按钮

头部操作按钮有,左侧插槽,放置添加、删除等按钮,右侧为若依系统封装的组件,含有重置、隐藏表单等按钮

<!-- 表格头部操作按钮 -->
    <el-row :gutter="10" class="mb8" v-if="isShowToolBar">
      <slot name="operate-list"></slot>
      <right-toolbar :showSearch.sync="isShowSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

3、表格数据展示 

表格封装分为, 表格选择、序号、文本列、列插槽,封装表格选中事件

tableColumns: [{
            dataKey: 'nickName',
            label: `用户昵称`,
          },
          {
            dataKey: 'status',
            label: `状态`,
            width: '150',
            scopedSlots: 'status',
            align: "center",
          },
          {
            dataKey: 'createDate',
            label: `创建时间`,
            width: '150',
            scopedSlots: 'date',
            align: "center",
          },
          {
            label: `操作`,
            width: '160',
            align: 'center',
            scopedSlots: 'operate',
          }
],

 

<!-- 表格内容 -->
    <el-table ref="customTable" v-loading="loading" :data="tableData" :height="tableHeight" :border="border"
      @cell-click="cellClick" @row-click="rowClick" :row-class-name="tableRowClassName"
      @sort-change="sortProp => $emit('sort-change', sortProp)" @selection-change="handleSelectionChange">
      <!-- 表格选择 -->
      <el-table-column type="selection" :width="selectionW" align="center" :selectable="selectableFn"
        v-if="hasSelection" />
      <!-- 序号 -->
      <el-table-column label="序号" type="index" :width="indexW" :index="indexFun" v-if="hasIndex" />
      <!-- 其他列 -->
      <template v-for="(column, index) in columns">
        <!-- 插槽列表项 -->
        <el-table-column v-if="column.scopedSlots&&column.visible" :key="index" :label="column.label"
          :width="column.width" :min-width="column.minWidth" :align="column.align || 'left'"
          :class-name="column.className" :fixed="column.fixed">
          <template v-slot="scope">
            <slot :scope="scope" :name="column.scopedSlots"></slot>
          </template>
        </el-table-column>
        <!-- 文本列表项 -->
        <el-table-column v-if="!column.scopedSlots&&column.visible" :key="index + 'key'" :prop="column.dataKey"
          :label="column.label" :width="column.width" :min-width="column.minWidth"
          :show-overflow-tooltip="column.showOverflowTooltip || false" :sortable="column.sortable"
          :align="column.align || 'left'" :class-name="column.className"></el-table-column>
      </template>
    </el-table>

 4、数据分页操作 

 <!-- 分页操作 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams[paginationConfig.pageNumKey]"
      :limit.sync="queryParams[paginationConfig.pageSizeKey]" @pagination="getList" />

5、组件完整代码

组件实例代码 

<template>
  <div class="table-container">
    <!-- 表格组件 -->
    <!-- @submit.native.prevent 阻止表单的默认提交行为 -->
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="medium" :inline="true"
      v-show="isShowSearch" :label-width="lableWidth">
      <!--表格头部筛选条件   -->
      <template v-for="(form, index) in queryForms">
        <!-- 表单插槽 -->
        <el-form-item v-if="form.scopedSlots" :label="form.label" :key="index + 'query'"  :prop="form.dataKey">
          <slot :scope="{ queryParams, form, handleQuery }" :name="form.scopedSlots"></slot>
        </el-form-item>
        <!-- 输入框筛选 -->
        <el-form-item v-else :label="form.label"  :key="index + 'query-key'" :prop="form.dataKey">
          <el-input v-model="queryParams[form.dataKey]" :placeholder="'请输入' + form.label" clearable
            @keyup.enter.native="handleQuery" @clear="handleQuery" style="width: 180px" />
        </el-form-item>
      </template>
      <!-- 表格筛选条件操作按钮   -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
        <slot name="export"></slot>
      </el-form-item>
    </el-form>
    <!-- 表格头部操作按钮 -->
    <el-row :gutter="10" class="mb8" v-if="isShowToolBar">
      <slot name="operate-list"></slot>
      <right-toolbar :showSearch.sync="isShowSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格内容 -->
    <el-table ref="customTable" v-loading="loading" :data="tableData" :height="tableHeight" :border="border"
      @cell-click="cellClick" @row-click="rowClick" :row-class-name="tableRowClassName"
      @sort-change="sortProp => $emit('sort-change', sortProp)" @selection-change="handleSelectionChange">
      <!-- 表格选择 -->
      <el-table-column type="selection" :width="selectionW" align="center" :selectable="selectableFn"
        v-if="hasSelection" />
      <!-- 序号 -->
      <el-table-column label="序号" type="index" :width="indexW" :index="indexFun" v-if="hasIndex" />
      <!-- 其他列 -->
      <template v-for="(column, index) in columns">
        <!-- 插槽列表项 -->
        <el-table-column v-if="column.scopedSlots&&column.visible" :key="index" :label="column.label"
          :width="column.width" :min-width="column.minWidth" :align="column.align || 'left'"
          :class-name="column.className" :fixed="column.fixed">
          <template v-slot="scope">
            <slot :scope="scope" :name="column.scopedSlots"></slot>
          </template>
        </el-table-column>
        <!-- 文本列表项 -->
        <el-table-column v-if="!column.scopedSlots&&column.visible" :key="index + 'key'" :prop="column.dataKey"
          :label="column.label" :width="column.width" :min-width="column.minWidth"
          :show-overflow-tooltip="column.showOverflowTooltip || false" :sortable="column.sortable"
          :align="column.align || 'left'" :class-name="column.className"></el-table-column>
      </template>
    </el-table>
    <!-- 分页操作 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams[paginationConfig.pageNumKey]"
      :limit.sync="queryParams[paginationConfig.pageSizeKey]" @pagination="getList" />
  </div>
</template>

<script>
  export default {
    name: 'Table',
    dicts: [],
    props: {
      idKey: {
        type: String,
        default: 'Id'
      },
      disableIds: {
        type: Array,
        default: function() {
          return []
        }
      },
      tableHeight: {
        type: String
      },
      dataKey: {
        type: String,
        default: 'data'
      },
      countKey: {
        type: String,
        default: 'totalCount'
      },
      lableWidth: {
        type: String,
        default: '84px'
      },
      queryForms: {
        type: Array,
        default: function() {
          return []
        }
      },
      // 分页参数key
      paginationConfig: {
        type: Object,
        default: function() {
          return {
            pageNumKey: 'pageNum',
            pageSizeKey: 'pageSize'
          }
        }
      },
      // 表格项配置
      /**
       * [{ dataKey: 'userId', label: `用户编号`, className: '' },
       *  { dataKey: 'userName', label: `用户名称`, showOverflowTooltip: true },
       * { dataKey: 'nickName', label: `用户昵称`, showOverflowTooltip: true },
       * { dataKey: 'dept.deptName', label: `部门`, showOverflowTooltip: true },
       * { dataKey: 'phonenumber', label: `手机号码`, width: '120' },
       * { dataKey: 'status', label: `状态`, scopedSlots: 'status' },
       * { dataKey: 'createTime', label: `创建时间`, width: '160', sortable: true },
       * { label: `操作`, width: '160', scopedSlots: 'operate', className: 'small-padding fixed-width'}]
       */
      columns: {
        type: Array,
        required: true
      },
      // 是否展示索引
      hasIndex: {
        type: Boolean,
        default: false
      },
      indexW: {
        type: String,
        default: '55'
      },
      indexMethod: Function,

      // 是否带有纵向边框
      border: {
        type: Boolean,
        default: false
      },
      // 是否要高亮当前行
      highlightCurrentRow: {
        type: Boolean,
        default: false
      },
      // 是否为斑马纹 table
      stripe: {
        type: Boolean,
        default: true
      },
      // 接口请求function
      api: {
        type: Function,
        required: true
      },
      // 	行的 className 的回调方法,也可以使用字符串为所有行设置一个固定的 className。
      tableRowClassName: {
        type: Function | String,
        default: ''
      },
      queryParams: {
        type: Object,
        required: true
      },
      selectionW: {
        type: String,
        default: '55'
      },
      hasSelection: {
        type: Boolean,
        default: false
      },
      showSearch: {
        type: Boolean,
        default: true
      },
      isShowToolBar: {
        type: Boolean,
        default: true
      },
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 表格数据
        tableData: [],
        isShowSearch: this.showSearch
      };
    },
    computed: {
      indexFun() {
        if (this.indexMethod) {
          return this.indexMethod;
        }
        return index => (this.queryParams[this.paginationConfig.pageNumKey] - 1) * this.queryParams[this
          .paginationConfig.pageSizeKey] + 1 + index;
      }
    },
    created() {
      this.getList();
    },

    methods: {
      // 选中禁用
      selectableFn(item) {
        var disable = true;
        if (this.disableIds.indexOf(item[this.idKey]) != -1) {
          disable = false;
        }
        return disable;
      },
      // 清除表格选项
      clearSelection() {
        this.$refs.customTable.clearSelection();
      },
      // 获取表格选中
      getSelection() {
        var selection = this.$refs.customTable.selection;
        return selection;
      },
      // 获取表格选中
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams[this.paginationConfig.pageNumKey] = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm');
        this.$emit('before-reset-query');
        this.$nextTick(() => {
          this.handleQuery();
        });
      },
      // 当某个单元格被点击时会触发该事件
      cellClick(row, column, cell, event) {
        this.$emit('cell-click', row, column, cell, event);
      },
      // 当某一行被点击时会触发该事件
      rowClick(row, event, column) {
        this.$emit('row-click', row, column, event);
      },
      getList() {
        this.loading = true;
        this.api(this.queryParams).then(response => {
          this.tableData = response.rows;
          this.total = parseInt(response.total);
          this.loading = false;
          this.$emit('req-success', response);
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.$emit('selection-change', selection);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .table-container {
    ::v-deep {
      .el-button--primary.is-plain {
        background-color: #fff;
        border-color: #1890ff;
      }

      .el-button--primary.is-plain:hover,
      .el-button--primary.is-plain:focus {
        background-color: #1890ff;
      }

      .el-select {
        width: auto;
      }
    }
  }
</style>

组件使用代码 

<template>
  <div>
    <DataTableComponent ref="tableList" lableWidth="80px" :api="tableApi" :queryForms="queryForms" :query-params="queryParams"
      :columns="tableColumns">
      <!-- 查询条件 -->
      <template v-slot:query-status="{ scope }">
        <el-select v-model="scope.queryParams.status" :placeholder="'请选择' + scope.form.label" @change="scope.handleQuery" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </template>

      <!-- 表格回显 -->
      <!-- 状态 -->
      <template v-slot:status="{ scope }">
        <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
          @change="handleStatusChange(scope.row)"></el-switch>
      </template>
      <!-- 创建时间 -->
      <template v-slot:date="{ scope }">
        <span>{{ parseTime(scope.row.createTime) }}</span>
      </template>
      <!-- 操作 -->
      <template v-slot:operate="{ scope }">
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </DataTableComponent>
  </div>
</template>

<script>
  import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
    deptTreeSelect
  } from "@/api/system/user";
  import DataTableComponent from "./DataTableComponent.vue"
  export default {
    dicts: ['sys_normal_disable'],
    components: {
      DataTableComponent
    },
    data() {
      return {
        tableApi: listUser,
        // 表单项
        queryForms: [{
            dataKey: 'nickName',
            label: `用户昵称`
          },
          {
            dataKey: 'status',
            label: `状态`,
            scopedSlots: 'query-status'
          }
        ],
        // 查询参数
        queryParams: {
          nickName:"",
          status:"",
          pageNum: 1,
          pageSize: 10,
        },
        tableColumns: [{
            dataKey: 'nickName',
            label: `用户昵称`,
            visible:true,
          },
          {
            dataKey: 'status',
            label: `状态`,
            width: '150',
            scopedSlots: 'status',
            align: "center",
            visible:true,
          },
          {
            dataKey: 'createDate',
            label: `创建时间`,
            width: '150',
            scopedSlots: 'date',
            align: "center",
            visible:true,
          },
          {
            label: `操作`,
            width: '160',
            align: 'center',
            scopedSlots: 'operate',
            visible:true,
          }
        ],
      }
    },
    methods: {
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
    }
  }
</script>

<style>
</style>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值