什么,你还不会 vue 表格跨页多选?

首先贴一段完整的代码

<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%;height:500px"
      @select="handleSelectChange"
      @select-all="handleSelectAllChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="日期"
        width="120"
        prop="date"
      />
      <el-table-column
        prop="name"
        label="姓名"
        width="120"
      />
    </el-table>
    <el-pagination
      background
      :current-page.sync="currentPage"
      layout="prev, pager, next"
      :total="1000"
      @current-change="currentChange"
    />
  </div>
</template>

<script>
export default {
  data () {
    return {
      currentPage: 1,
      crossPageMap: new Map(),
      pageSize: 10,
      totalData: Array.from({ length: 1000 }, (_, index) => {
        return {
          date: '2016-05-03',
          id: index,
          name: '王小虎' + index
        }
      })
    }
  },
  computed: {
    tableData () {
      const { currentPage, totalData, pageSize } = this
      return totalData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    }
  },
  methods: {
    currentChange (page) {
      this.currentPage = page
      this.tableData.forEach(row => {
        const checked = this.crossPageMap.has(row.id)
        if (checked) this.$refs.multipleTable.toggleRowSelection(row, true)
      })
    },
    handleSelectChange (val, row) {
      const checked = this.crossPageMap.has(row.id)
      if (checked) {
        this.crossPageMap.delete(row.id)
      } else {
        this.crossPageMap.set(row.id, row)
      }
    },
    handleSelectAllChange (val) {
      this.tableData.forEach(row => {
        const isChecked = this.crossPageIns.isChecked(row)
        if (val.length === 0) {
          // 取消全选 只有选中的需要改变状态
          if (isChecked) this.crossPageIns.onRowSelectChange(row)
        } else {
          // 全选 只有未选中的才需要改变状态
          if (!isChecked) this.crossPageIns.onRowSelectChange(row)
        }
      })
    }
  }
}
</script>

然后稍稍解释一波吧
参数:

`data` - 行数据
`key` - 行数据唯一值
`max` - 最大选中行数
`toggleRowSelection` - 切换行数据选中/取消选中的方法

方法:

`onRowSelectChange` - 外部点行数据点击的时候调用此方法
`onDataChange` - 外部数据变化的时候调用此方法
`clear` - 清空所有选中行
`isChecked` - 判断当前行是否选中

构造器大致代码 如下:

constructor (options={}) {
    this.crossPageMap = new Map()
    this.key = options.key || 'id'
    this.data = options.data || []
    this.max = options.max || Number.MAX_SAFE_INTEGER
    this.toggleRowSelection = options.toggleRowSelection
    if(typeof this.toggleRowSelection !== 'function') throw new Error('toggleRowSelection is not function')
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值