element UI中table表格在选中数据后点击分页,再选中数据,回到第一页后,原来选中的数据已经不再是勾选状态了,现在要怎样记住所有分页中的勾选状态呢?我这里有比较简便的方法。不需要缓存数据等复杂的方式。

1、首先在table标签上定义row-key和ref标志名称。具体row-key等功效,可以参考element UI文档。代码如下:

 <el-table
          ref="table"
          v-loading="loading"
          :data="dataList"
          row-key="id"
          @select="selectItem"
          @select-all="selectAll"
        >
          <el-table-column
            key="1"
            type="selection"
            width="40"
            reserve-selection
          />
</el-table>

2、定义选择单列(selectItem)和全选(selectAll)的方法。代码如下:

selectItem(list, row) {
    this.checkList = list
}

把当前页选中的数据保存到checkList数组中,该数据仅保存的是当前页选中数据。(若切换分页选中,数据会被覆盖为最新选中数据)

 selectAll(selection) {
      // 若取消全选,当前页的选中数据移除
      if (selection.length === 0) {
        const ids = this.dataList.map((i) => {
          return i.id
        })
        for (var i = 0; i < this.checkList.length; i++) {
          if (ids.indexOf(this.checkList[i].id) > -1) {
            this.checkList.splice(i, 1)
            i--
          }
        }
      }
      const arr = [...selection, ...this.checkList]
      this.checkList = Array.from(new Set(arr))
},

全选的方法中,需要判断是勾选还是取消勾选。若取消勾选,需要把当前页选中的数据全部清空。

3、清空所有选中的数据方式。代码如下:

this.$refs.table.clearSelection()
this.checkList = []

清空表格中选中项,再清空选中数组。

这种处理方式,就可以在分页时依然记得之前选中的数据,返回原来分页数据还在,全选选中与否,数据都可以随之修改。nice~~

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。