element ui 表格分页二次封装使用mixins/表格全选单选二次封装使用mixins

<template>
  <div class="test-table-box mt20">
    <el-table
      stripe
      :data="list"
      :height="tableHeight"
      border
      style="width: 100%"
      ref="multipleTable"
      tooltip-effect="dark"
      v-loading="loading"
      element-loading-text="数据正在加载中"
      @select="onTableSelect"
      @select-all="onTableSelectAll"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="序号" width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index +1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="测试名称" align="center" show-overflow-tooltip></el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page_box fr mt20">
      <el-pagination
        class="el-paging"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pagesizeList"
        :page-size="pagesize"
        :layout="pageLayout"
        :total="total"
        :background="pageBackground"
      ></el-pagination>
    </div>
    <!-- 可以视情况要不要占位 -->
    <div style="height:60px;"></div>
  </div>
</template>
// import { pageSearchMixin } from '@/components/mixins/pageSearch'
// mixins: [pageSearchMixin],

// 分页、查询
import { mapState } from 'vuex'
export const pageSearchMixin = {
    data() {
        return {
            loading: false,
            list: [], // 列表数据
            currentPage: 1, // 当前页数
            pagesize: 10, // 每页显示多少条
            pagesizeList: [10, 20, 50, 100],
            pageLayout: "total, sizes, prev, pager, next, jumper",
            pageBackground: true,
            total: 0,  // 默认数据总数
            isCreated: false  // 是否初始化需要调接口
        }
    },
    methods: {
        // 页码
        _initListData(currentPage = this.currentPage, pagesize = this.pagesize) {
            this.currentPage = currentPage;
            this.pagesize = pagesize;
            this._requestPageList({
                pageNo: currentPage,
                pageSize: pagesize,
            })
        },
        // 列表接口
        _requestPageList(pageData) { },
        // 每页
        handleSizeChange(size) {
            this.pagesize = size;
            this._initListData(1, size)
            //console.log(`每页 ${val} 条`);
        },
        // 当前页
        handleCurrentChange(currentPage) {
            this._initListData(currentPage)
            //console.log(`当前页: ${val}`);
        },
        //查询数据
        searchData() {
            // console.log('查询成功')
            // 默认从第一页开始查询
            this._initListData(1);
        },
    },
    created() {
        if (this.isCreated) {
            return
        }
        this._initListData();
    },
    computed: {
        ...mapState({
            // 表格高度依据布局来(可忽略---依据情况来---建议最好不要混入在这里面因为融合了vuex)
            tableHeight: state => state.searchCriteria.contentBoxHeight - 160
        })
    }
}
// 组件调用 分页js逻辑
<script> import { pageSearchMixin } from '@/components/mixins/pagingSearch'; import { testApi } from "@/http/testApi"; import { mapState } from 'vuex' export default { mixins: [pageSearchMixin], // 分页公共 data () { return { isCreated: true, // 如果初始化不需要调用接口就传true进去 pagesize: 8, //每页显示多少条 pagesizeList: [8, 16, 24, 32], // 页码 } }, computed: { ...mapState({ tableHeight: state => state.searchCriteria.contentBoxHeight - 196 }) }, created () { }, methods: { // 如果列表操作需要查询的调用 this._initListData(1)或者 searchData()即可
    // 图片列表数据
    _requestPageList(pageData) {
      const data = {
        id:{ id: this.$route.query.id},
        pageData
      };
      this.loading = true;
      testApi(data).then(res => {
        if (res.data.returnResult === 200) {
          this.loading = false;
          this.list = res.data.returnData.data.map(e => {
            return {
              id: e.id,
              name: e.name
            }
          })
          // console.log(this.list,'this.list')
          this.total = res.data.returnData.recordCount;
        }
      })
    }
  }
}
</script>
// import { tableSelectMixin } from '@/components/mixins/tableSelect'
// mixins: [tableSelectMixin],

export const tableSelectMixin = {
    data() {
        return {
            checkResList: [],
            innerVisible: true,
        }
    },
    methods: {
        closeEvt() {
            this.innerVisible = true;
            this.$emit('confirmEvt');
        },
        submitEvt() {
// 确认回调数据
this.$emit('confirmEvt', true, this.checkResList); }, // 取消默认选中项(单个勾选) /** *checkResList 接口返回的默认勾选数组 *id 列表唯一标识 */ onTableSelect(rows, row) { // console.log(rows,'rows',row,'row') if (!rows.includes(row)) { const index = this.checkResList.findIndex(item => { return item.id === row.id }); this.checkResList.splice(index, 1) } else { this.checkResList.push(row) } }, // 全选操作 onTableSelectAll(arr) { // console.log(arr,'全选or取消全选') if (!arr.length) { // 直接取消选中全部 this.list.forEach((v) => { const index = this.checkResList.findIndex(i => { return i.id === v.id }) if (index !== -1) { this.checkResList.splice(index, 1) } }) } else { // 直接选中全部 this.list.forEach((v) => { const index = this.checkResList.findIndex(i => { return i.id === v.id }) if (index === -1) { this.checkResList.push(v) } }) } }, // 回显 _toggleRowSelecteMixin(isCheck = false) { let _this = this; this.list.forEach(e => { let rIndex = _this.checkResList.findIndex(ele => { return ele.id === e.id }); if (rIndex > -1) { if (isCheck) { // 如果列表的值可以改变,需要重新勾选以绑定改变的值 _this.checkResList.splice(rIndex, 1, e); } _this.$nextTick(() => { _this.$refs.multipleTable.toggleRowSelection(e, true);//这个就是回显的核心 }) } }) } } }
<script>
// 注明:我的弹窗弹出来的选择单选/全选/跨页勾选的情况其他的请自行对应数据修改(以下为组件调用)
import { testList } from "@/http/tesApi";
import { tableSelectMixin } from "@/components/mixins/tableSelect";
export default {
  mixins: [tableSelectMixin],
  props: {
    checkList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      name: ""
    };
  },
  created() {
    this.checkResList = JSON.parse(JSON.stringify(this.checkList));
    // console.log('checkResList',this.checkResList)
  },
  methods: {
    // 列表接口
    _requestPageList(pageData) {
      let data = {
        pageData,
        name: this.name
      };
      // console.log('data',data)
      // return
      this.loading = true;
      testList(data).then(res => {
        if (res.data.returnResult == 200) {
          this.loading = false;
          this.list = (res.data.returnData.data || []).map(e => {
            return {
              id: e.id,
              name: e.name
            };
          }); //赋值列表数据
          this.total = res.data.returnData.recordCount; //设置数据总数目!!!
          this._toggleRowSelecteMixin(); //mixins表格回显
        }
      });
    }
  }
};
</script>
<template>
  <div class="test-table-box mt20">
    <el-table
      :data="list"
      ref="multipleTable"
      style="width: 100%"
      tooltip-effect="dark"
      :row-key="row => row.id"
      @selection-change="handleSelect"
      border
    >
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
      <el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip></el-table-column>
    </el-table>
  </div>
</template>
<script>
// table上加 :row-key="row => row.id" 这条数据的区别字段 只要是唯一属性即可
// type="selection" 加上 :reserve-selection="true" 和回显哪行代码是核心
import { testList } from "@/http/testApi";
export default {
  props: {
    resIdList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      list: [],
      multipleSelection: []
    };
  },
  mounted() {},
  methods: {
    // 选中  @selection-change="handleSelect" 只需这个方法即可
    handleSelect(val) {
      // console.log(val,'选中')
      this.multipleSelection = val;
    },
    // 确认
    sureData() {
      this.dialogVisible = false;
      this.$emit("handleSelect", this.multipleSelection);
    },
    // 列表数据
    getList() {
      let _this = this;
      const data = {
        xx: xx,
        xx: xx
      };
      // 简单版本跨页勾选---使用情况一般单选多选全选跨页全选的导出、没有数据回显的新增等简单场景简单粗暴(要数据回显的不建议使用)
      testList(data).then(res => {
        if (res.data.returnResult === 200) {
          this.list = res.data.returnData.data || [];
          this.total = res.data.returnData.recordCount;
          // this.list 列表数据循环 _this.resIdList 后台回显数据集合循环对比使用toggleRowSelection选中
          this.list.forEach((e, i) => {
            (_this.resIdList || []).forEach((k, j) => {
              if (_this.resIdList[j].id == _this.list[i].id) {
                _this.$nextTick(() => {
                  _this.$refs.multipleTable.toggleRowSelection( _this.list[i], true); //这个就是回显的核心
                });
              }
            });
          });
        }
      });
    }
  }
};
</script>
  // 有的时候你不想使用复杂的mixins可以直接使用下面两个方法即可实现跨页勾选 以及数据回显 适用任何情况
  methods: {
    // 取消默认选中项(单个勾选)
    /**
   *selectResList 接口返回的默认勾选数组
    *id 列表唯一标识
    */ 
    onTableSelect (rows, row) {
      // console.log(rows,'rows',row,'row')
      if (!rows.includes(row)) {
        const index = this.selectResList.findIndex(item =>         
          item.id=== row.id)
            this.selectResList.splice(index, 1)
      } else {
        this.selectResList.push(row)
      }
    },
    // 全选操作
    onTableSelectAll (arr) {
      // console.log(arr,'全选or取消全选')
      if (!arr.length) { // 直接取消选中全部
        this.list.forEach((v) => {
          const index = this.selectResList.findIndex(i => 
              i.id === v.id)
          if (index !== -1) {
            this.selectResList.splice(index, 1)
          }
        })
      } else { // 直接选中全部
        this.list.forEach((v) => {
          const index = this.selectResList.findIndex(i => 
              i.id=== v.id)
          if (index === -1) {
            this.selectResList.push(v)
          }
        })
      }
    },
  }
posted @ 2020-01-14 11:21  鱼樱前端  阅读(936)  评论(0编辑  收藏  举报