element封装一个 结合form/table/pagination于一身的公共组件

本文介绍了一种封装Element UI的el-form、el-table和el-pagination组件的方法,以减少代码冗余并提高开发效率。该组件支持自定义列配置、分页、筛选及操作栏等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:现在写后台很多页面的列表长的都比较像,避免代码冗余,现将el-form、el-table、el-pagination封装在一个组件中。这样用起来也比较方便。
上代码
一、主体部分

<style lang="scss">
.TablePageContainer {
  .inner_content {
    width: 100%;
    overflow: hidden;
  }
  .el-table__fixed,
  .el-table__fixed-right {
    height: auto !important;
    bottom: 17px;
  }
}
</style>

<template>
  <div class="main__right__inner TablePageContainer" ref="content">
    <div class="main__right__content">
      <h2 class="list--name">{{ $route.name }}</h2>
      <ol v-if="tabshow" class="el-tabs" ref="elTabs">
        <span v-for="(item, index) in tabListUsed" :key="index">
          <li
            :class="{ active: activeName === item.code }"
            @click="changeTabs(item.code)"
          >
            <span>{{ item.text }}</span>
          </li>
        </span>
      </ol>
      <!-- 搜索表单 -->
      <slot name="form" :activeName="activeName"> </slot>
      <!-- 列表 -->
      <template title="列表">
        <el-table
          :data="tableData"
          stripe
          class="my__table"
          ref="Table"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
          @select="handleSelect"
        >
          <template slot="empty">
            <div class="el-empty">
              <div class="el-empty__icon"></div>
              <div class="el-empty__text">{{ emptyText }}</div>
            </div>
          </template>
          <el-table-column v-if="selection" type="selection" width="55">
          </el-table-column>
          <!-- 列表数据 -->
          <el-table-column
            v-for="(item, index) in tableTitleList"
            :key="index"
            :min-width="item.minWidth"
            :prop="item.prop"
            :show-overflow-tooltip="item.tipShow"
            :label="item.title"
            :fixed="item.fixed"
          >
            <template slot-scope="scope">
              <slot name="tableItem" :scope="scope" :item="item"></slot>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!hideOptions"
            :min-width="optionsWidth"
            :show-overflow-tooltip="true"
            label="操作"
            fixed="right"
          >
            <template slot-scope="scope">
              <div>
                <slot name="options" :scope="scope"></slot>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template title="分页">
        <slot name="pagination"></slot>
      </template>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  props: [
    "tableData",
    "tableTitleList",
    "advancedQueryShow",
    "tabList",
    "optionsWidth",
    "selection",
    "queryFormHeight",
    "hideOptions",
  ],
  watch: {
    advancedQueryShow() {
      window.onresize();
    },
  },
  computed: {
    // 判断有没有tab页
    tabshow() {
      return this.tabList && this.tabList.length;
    },
    //默认tab页
    tabListUsed() {
      if (this.tabshow) {
        // 判断有没有权限限制
        if (this.tabList[0].checkRes) {
          let arr = this.tabList.filter((item) => {
            return item.code !== -1 && this.checkRes(item.checkRes);
          });
          if (arr && arr.length === this.tabList.length - 1) {
            arr.unshift(this.tabList[0]);
          }
          this.activeName = arr && arr.length ? arr[0].code : "";
          return arr;
        } else {
          this.activeName = this.tabList[0].code;
          return this.tabList;
        }
      } else {
        return [];
      }
    },
  },
  // 数据源
  data() {
    //监听窗口尺寸变化改变高级搜索框的宽度
    window.onresize = () => {
      if (this.advancedQueryShow) {
        this.tableHeight =
          window.innerHeight -
          (this.queryFormHeight ? this.queryFormHeight : 360);
      } else {
        this.tableHeight =
          window.innerHeight -
          (this.queryFormHeight ? this.queryFormHeight : 310);
      }
    };
    return {
      emptyText: "暂无数据",

      //顶部tab标签页选中标记  默认取第一个
      activeName: "",

      // 列表的高度
      tableHeight: "550", //列表高度
    };
  },
  created() {},

  // 组件渲染完执行
  mounted() {
    setTimeout(() => {
      window.onresize();
    }, 100);
  },

  // 自定义方法
  methods: {
    // 列表选中状态变化回调
    handleSelectionChange(val) {
      this.$emit("selectionChange", val);
    },

    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    handleSelect(selection, row) {
      this.$emit("handleSelect", selection, row);
    },

    // 手动设置列表选中状态  用于跨页面选中列表数据
    // data:已选中的数据集合
    // identification:列表关联字段标识,用来筛选当前分页里的数据
    toggleRowSelection(data, identification) {
      if (this.tableData && this.tableData.length && data && data.length) {
        this.tableData.forEach((item) => {
          data.forEach((_item) => {
            if (item[identification] === _item[identification]) {
              this.$refs.Table.toggleRowSelection(item, true);
            }
          });
        });

        this.$emit("selectOver")
      }
    },

    // 顶部标签页切换
    changeTabs(val) {
      this.activeName = val;
      this.$emit("tabChange", val);
    },
  },
};
</script>

二、使用

<TablePageContainer
      ref="TablePageContainer"
      :tableData="tableData"
      :tableTitleList="tableTitleList"
      :hideOptions="false"
      :optionsWidth="200"
      :selection="true"
      :queryFormHeight="queryFormHeight"
      @selectionChange="selectionChange"
      @selectOver="selectOver"
    >
      <template v-slot:form="{}">
        <el-row class="search_form_container">
          <el-form ref="form" :model="param" label-width="105px">
            <div
              class="left_form"
              :style="`${'padding-right:' + optionWidth + 'px'}`"
            >
              <!-- 默认搜索项 -->
              <el-form-item label="####" class="el-col-8">
                <el-input
                  placeholder="#####"
                  v-model.trim="param.projectName"
                  clearable
                ></el-input>
              </el-form-item>

              <el-form-item label="#####" class="el-col-8">
                <el-select
                  v-model="param.areaCode"
                  placeholder="####"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in areaCodeList"
                    border
                    :label="item.text"
                    :value="item.code"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div
              class="right_options"
              :style="`${'width:' + optionWidth + 'px'}`"
            >
              <el-form-item class="el-col-24" label-width="0">
                <el-button type="primary" plain @click="listSearch"
                  >查询</el-button
                >
                <el-button plain @click="reset">重置</el-button>
              </el-form-item>
              <el-form-item class="el-col-24" label-width="0">
                <el-button type="primary" @click="add">新增</el-button>
                <el-button type="primary" @click="leadingIn">导入</el-button>
                <el-button type="primary" @click="merge">合并</el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-row>
      </template>
	// 循环列  并 可以特殊处理某个列
      <template v-slot:tableItem="{ scope, item }">
        <div v-if="item.title === '序号'" class="table_td_item_content">
          <span>
            {{ scope.$index + 1 + (param.page - 1) * param.pageSize }}
          </span>
        </div>
        <div
          v-else-if="item.title === '未立项项目名称'"
          class="table_td_item_content"
        >
          <a href="javascript:;" @click="enterDetail(scope.row)" v-if="scope.row.projectName">
            {{ scope.row.projectName }}
          </a>
        </div>
        <div
          v-else-if="item.title === '项目状态'"
          class="table_td_item_content"
        >
          <span v-if="scope.row.status == 0">已作废</span>
          <span v-if="scope.row.status == 1">正常</span>
        </div>

        <!-- 默认无操作的列 -->
        <div class="table_td_item_content" v-else>
          {{ scope.row[item.prop] }}
        </div>
      </template>
	// 操作部分
      <template v-slot:options="{ scope }">
        <div v-if="scope.row.status == 1 && scope.row.relateFlag == 1">
          <a href="javascript:;">
            <span @click="relieve(scope.row)">解除关联</span>
          </a>
        </div>
      </template>

      <template #pagination>
        <el-pagination
          :total="total"
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page.sync="param.page"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="param.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </template>
    </TablePageContainer>
/*  需要传递参数的注释
* tableData:Array  表格中的数据
* tableTitleList: Array  需要循环的列
* selection:Boolean  是否显示复选框
* hideOptions:Boolean  是否显示操作栏
* optionsWidth:Number  操作栏宽度
* queryFormHeight:Number  el-table高度
* selectionChange:function  复选框change事件
*/
// tableTitleList如果过长  建议在外部定义,格式如下

三、引入需要循环的列

export const tableTitleList = [
    // { title: "序号", minWidth: 60, tipShow: true, fixed: true },
    {
        title: "###",  // 列名
        prop: "###",  // 字段名
        minWidth: 180,  // 列宽
        tipShow: true,  // 是否显示tooltip
        fixed: false  // 是否固定列
    },
    {
        title: "###",
        prop: "###",
        minWidth: 180,
        tipShow: true,  
        fixed: false
    },
]

有什么问题欢迎留言 感谢

可以参考下面的代码,这是一个基于Vue 2.0和Element UI的表格和搜索条件的公共组件: ```vue <template> <div> <el-form v-if="showFilter" :inline="true" :model="filterForm" class="demo-form-inline"> <el-form-item v-for="item in filterItems" :label="item.label" :key="item.prop"> <el-input v-if="item.type === 'input'" v-model="filterForm[item.prop]" :placeholder="item.placeholder"></el-input> <el-select v-if="item.type === 'select'" v-model="filterForm[item.prop]" :placeholder="item.placeholder"> <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="filter">查询</el-button> <el-button @click="resetFilter">重置</el-button> </el-form-item> </el-form> <el-table :data="tableData" :columns="tableColumns" :highlight-current-row="highlightCurrentRow" :row-class-name="rowClassName" :row-style="rowStyle" :row-key="rowKey" :header-cell-style="headerCellStyle" :default-sort="defaultSort" :show-header="showHeader" :show-summary="showSummary" :sum-text="sumText" :summary-method="summaryMethod" :border="border" :stripe="stripe" :size="size" :fit="fit" :empty-text="emptyText" :loading="loading" :row-selection="rowSelection" :expand-row-keys="expandRowKeys" :tree-props="treeProps" @row-click="rowClick" @row-dblclick="rowDblclick" @current-change="currentChange" @select="select" @select-all="selectAll" @selection-change="selectionChange" @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave" @cell-click="cellClick" @cell-dblclick="cellDblclick" @header-click="headerClick" @header-contextmenu="headerContextmenu" @sort-change="sortChange" @filter-change="filterChange" @expand-change="expandChange" @select-toggle-all="selectToggleAll" @select-toggle-row="selectToggleRow" @row-contextmenu="rowContextmenu" @header-dragend="headerDragend" @row-dragend="rowDragend" @row-dragenter="rowDragenter" @row-dragleave="rowDragleave" @row-dragover="rowDragover" @row-drop="rowDrop" ref="table"> <slot></slot> </el-table> <div v-if="showPagination" class="demo-pagination"> <el-pagination :page-size="pagination.pageSize" :total="pagination.total" :current-page.sync="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination> </div> </div> </template> <script> export default { name: 'TableWithFilter', props: { tableData: { type: Array, required: true }, tableColumns: { type: Array, required: true }, pagination: { type: Object, default: () => { return { pageSize: 10, total: 0, currentPage: 1 } } }, filterItems: { type: Array, default: () => [] }, showFilter: { type: Boolean, default: true }, showPagination: { type: Boolean, default: true }, highlightCurrentRow: Boolean, rowClassName: Function, rowStyle: [Object, Function], rowKey: [String, Function], headerCellStyle: [Object, Function], defaultSort: Object, showHeader: { type: Boolean, default: true }, showSummary: Boolean, sumText: String, summaryMethod: Function, border: Boolean, stripe: Boolean, size: String, fit: { type: Boolean, default: true }, emptyText: String, loading: Boolean, rowSelection: Object, expandRowKeys: Array, treeProps: Object }, data() { return { filterForm: {} } }, methods: { filter() { this.$refs.table.setCurrentRow(null) this.$emit('filter', this.filterForm) }, resetFilter() { this.filterForm = {} this.filter() }, handleSizeChange(val) { this.$emit('size-change', val) }, handleCurrentChange(val) { this.$emit('current-change', val) }, rowClick(row, column, event) { this.$emit('row-click', row, column, event) }, rowDblclick(row, event) { this.$emit('row-dblclick', row, event) }, currentChange(currentRow, oldCurrentRow) { this.$emit('current-change', currentRow, oldCurrentRow) }, select(selection, row) { this.$emit('select', selection, row) }, selectAll(selection) { this.$emit('select-all', selection) }, selectionChange(selection) { this.$emit('selection-change', selection) }, cellMouseEnter(row, column, cell, event) { this.$emit('cell-mouse-enter', row, column, cell, event) }, cellMouseLeave(row, column, cell, event) { this.$emit('cell-mouse-leave', row, column, cell, event) }, cellClick(row, column, cell, event) { this.$emit('cell-click', row, column, cell, event) }, cellDblclick(row, column, cell, event) { this.$emit('cell-dblclick', row, column, cell, event) }, headerClick(column, event) { this.$emit('header-click', column, event) }, headerContextmenu(column, event) { this.$emit('header-contextmenu', column, event) }, sortChange({ column, prop, order }) { this.$emit('sort-change', { column, prop, order }) }, filterChange(filters) { this.$emit('filter-change', filters) }, expandChange(row, expandedRows) { this.$emit('expand-change', row, expandedRows) }, selectToggleAll(selection) { this.$emit('select-toggle-all', selection) }, selectToggleRow(row, selected) { this.$emit('select-toggle-row', row, selected) }, rowContextmenu(row, event) { this.$emit('row-contextmenu', row, event) }, headerDragend(newWidth, oldWidth, column, event) { this.$emit('header-dragend', newWidth, oldWidth, column, event) }, rowDragend(newIndex, oldIndex, row, event) { this.$emit('row-dragend', newIndex, oldIndex, row, event) }, rowDragenter(dropPosition, drag, event) { this.$emit('row-dragenter', dropPosition, drag, event) }, rowDragleave(dropPosition, drag, event) { this.$emit('row-dragleave', dropPosition, drag, event) }, rowDragover(dropPosition, drag, event) { this.$emit('row-dragover', dropPosition, drag, event) }, rowDrop(dropPosition, drag, event) { this.$emit('row-drop', dropPosition, drag, event) } } } </script> <style scoped> .demo-form-inline .el-form-item { margin-right: 20px; } .demo-pagination { margin-top: 20px; text-align: right; } </style> ``` 使用方法: ```vue <template> <div> <table-with-filter :table-data="tableData" :table-columns="tableColumns" :pagination="pagination" :filter-items="filterItems"></table-with-filter> </div> </template> <script> import TableWithFilter from '@/components/TableWithFilter' export default { components: { TableWithFilter }, data() { return { tableData: [], tableColumns: [{ prop: 'name', label: '名称' }, { prop: 'age', label: '年龄' }], pagination: { pageSize: 10, total: 0, currentPage: 1 }, filterItems: [{ prop: 'name', label: '名称', placeholder: '请输入名称', type: 'input' }, { prop: 'age', label: '年龄', placeholder: '请选择年龄', type: 'select', options: [{ label: '18岁以下', value: '<=18' }, { label: '19-30岁', value: '19-30' }, { label: '31岁以上', value: '>=31' }] }] } }, methods: { fetchData() { // 获取数据并更新tableData和pagination.total }, handleFilter(params) { // 处理搜索条件 }, handleSizeChange(size) { this.pagination.pageSize = size this.fetchData() }, handleCurrentChange(page) { this.pagination.currentPage = page this.fetchData() } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值