ElementUI中Table组件分页多选的回显问题

重要的事情说三遍:看文档!看文档!看文档!

项目场景:

后期维护项目的时候,有用户反馈,一个长列表页等待加载时间特别长,操作卡顿,希望优化一下
到线上查看页面,一直在loading等了十多秒数据才出现


原因分析:

打开f12
先看看网络,后台接口耗时300ms左右,返回数据3000左右,没什么问题
再看看性能,发现渲染花了3566ms,这就有问题了
3000左右的数据量,页面加载确实很慢,那就换个分页的接口试试
十条数据一页,页面就很丝滑了


解决方案:

换个分页接口,解决了。(当时也没多想,换个接口就完了,毕竟不是自己写的页面,完全不知道有个编辑多选框复选的问题)


后续

一段时间后,有用户反应这个页面的编辑有问题
明明之前选了一些数据,点编辑,之前选的数据全没了,要重新选。再点下一页,突然多出几条数据

原因分析:

页面部分代码

  <!-- table部分 -->
  <el-table :data="listInfo.dataList" border stripe v-loading="listInfo.listLoading" @selection-change="handleSelectionChange" height="600px"
    :row-key="getRowKeys" ref="multipleTable">
    <el-table-column reserve-selection="true" type="selection" align="center" width="50"></el-table-column>
    <el-table-column type="index" width="50" label="序号"></el-table-column>
    <el-table-column align="center" prop=deviceName label="设备名称"></el-table-column>
    <el-table-column align="center" prop=companyName label="企业名称"></el-table-column>
  </el-table>
  
  <!-- tag统计 -->
  <div class="selectRow pt10" v-show="tableSelectionList && tableSelectionList.length > 0">
    已选中<span>{{ tableSelectionList.length }}</span>条,
    <el-badge class="item mr10 mb5" v-for="(i,index) in selectListInfo" type="primary" :key="index" :value="i.num">{{i.text}}</el-badge>
  </div>
  data() {
    return {
      listInfo: {	// 列表
        dataList: [],
        listLoading: false,
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      tableSelectionList: [], //列表中选中的数据
      selectListInfo: [], // tag统计数据
    }
  },
  props: {
    selectionList: {	// 上一次提交的数据
      required: false,
      default: ()=> []
    }
  },
  watch: {
    selectionList:{
      handler(val){
        this.tableSelectionList = val
      },
      immediate: true
    }
  },
  methods: {
    // 获取列表
    getTableList() { 
      this.listInfo.listLoading = true
      let params = Object.assign({}, {
        limit: this.listInfo.pageSize,
        page: this.listInfo.currentPage,
      })
      getList(params).then(({ result }) => {
        this.listInfo.dataList = result.list
        this.listInfo.total = result.totalCount
        this.listInfo.listLoading = false
        this.toggleSelection(this.selectionList)
      }).catch((value) => {
        this.listInfo.dataList = []
        this.listInfo.total = 0
        this.listInfo.listLoading = false
      })
    },
    // 反选处理--回显数据
    toggleSelection(rows) {
      if (rows.length > 0) {
        this.$nextTick(() => {
          rows.forEach(row => { //回显数据
            let selectData = this.listInfo.dataList.find(item => row.comId === item.comId)
            if (selectData) this.$refs.multipleTable.toggleRowSelection(selectData, true)
          })
          this.getSelectListInfo(this.tableSelectionList)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 择项发生变化
    handleSelectionChange(val) {
      this.tableSelectionList = val
      this.getSelectListInfo(this.tableSelectionList)
    },
    // 统计tag个数
    getSelectListInfo(val) { 
      this.selectListInfo = []
      let arr = []
      val.map(i => arr.push(i.companyName))
      let map = arr.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map())
      map.forEach((value, key) => {
        this.selectListInfo.push({
          text: key,
          num: value
        })
      })
    },
  }
  	

点编辑,之前选的数据全没了,要重新选,描述不准确
BUG:点击编辑,只保留第一页的数据,其余数据全消失。点下一页,保留了第一页和下一页的数据

点击编辑,只保留第一页的数据,其余数据全消失的原因:
每次切换页数调getTableList获取下一页数据,拿到后台返回的数据后调toggleRowSelection(table的内置方法)进行回显,改变了选中的数据,触发了selection-change事件,影响选中的列表tableSelectionList 和展示的列表selectListInfo

点下一页,保留了第一页和下一页的数据的原因:
reserve-selection这个属性
Element官方描述:reserve-selection :仅对 type=selection 的列有效,类型为 Boolean,为 true 则会在数据更新之后保留之前选中的数据(需指定 row-key)
顺带解释下selection-change 这个事件。官方描述:selection-change : 当选择项发生变化时会触发该事件
即无论是用户手动选择还是调用API使选中数据发生变化,都会触发这个事件

reserve-selection 在数据更新之后保留之前选中的数据 这意味着每次选中数据发生变化,我们都可以在 selection-change 中拿到之前选中的所有数据,这样就保留了上一次选中的数据。点下一页看起来就是突然多了好几条数据就是因为把之前选的数据复显了
(ps:如果放在单页多选中,有无reserve-selection这个属性对于我们在selection-change中能拿到的数据没有影响)

更多属性和方法见官方文档 ElementUI Table组件


解决方案

知道具体问题在哪,就不难了
首先能顺着想到的就是,分情况操作数据

1.对于没有传入selectionList的长度为0,为新增操作,也不需要回显数据
2.对于没有传入selectionList的长度大于0,为编辑操作,需要回显数据
3.添加一个addFlag变量,true 时为新增操作,false 为编辑操作,这里我放在watch里面进行初始化
  watch: {
    selectionList:{
      handler(val){
        this.tableSelectionList = val
        this.addFlag = val.length == 0	// 初始化 addFlag
      },
      immediate: true
    }
  },

addFlag使用的地方应在selection-change

4.进行选中数据复显,selection-change触发的时机是this.$refs.multipleTable.toggleRowSelection(selectData, true)之后

为方便搞清楚具体触发时机可以:

    // 反选处理--回显数据
    toggleSelection(rows) {
      if (rows.length > 0) {
        console.log(this.tableSelectionList, 'before tableSelectionList');
        this.$nextTick(() => {
          rows.forEach(row => { //回显数据
            let selectData = this.listInfo.dataList.find(item => row.comId === item.comId)
            if (selectData) this.$refs.multipleTable.toggleRowSelection(selectData, true)
          })
          //  tableSelectionList 数据更新完毕
          console.log(this.tableSelectionList, 'after tableSelectionList');
          this.getSelectListInfo(this.tableSelectionList)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 择项发生变化
    handleSelectionChange(realList) {
      console.log(realList, 'realList');
      this.tableSelectionList = realList
      this.getSelectListInfo(this.tableSelectionList)
    },

在这里插入图片描述

显然我们不希望tableSelectionList在复显的时候发生变化,可以引入一个中间量,存一下,然后再赋值回去,这样反选处理就完成了

    // 反选处理--回显数据
    toggleSelection(rows) {
      if (rows.length > 0) {
        let tempList = this.tableSelectionList
        this.$nextTick(() => {
          rows.forEach(row => { //回显数据
            let selectData = this.listInfo.dataList.find(item => row.comId === item.comId)
            if (selectData) this.$refs.multipleTable.toggleRowSelection(selectData, true)
          })
          //  tableSelectionList 数据更新完毕
          this.tableSelectionList = tempList
          this.getSelectListInfo(this.tableSelectionList)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
5.对于selection-change

首先要明白择项发生变化就会触发,即用户选中和取消选中都会触发
那么如何判断用户是选中和取消选中呢?
可以比较上一次选中的数据和这一次选中的数据
添加一个oldList变量,用于保存上一次table组件选中的数据,初始化为[]
选中的话,这次选中的数据长度大于上一次选中的数据长度。反之取消选中的话,这次选中的的数据长度小于上一次选中的数据长度

	// 择项发生变化
    handleSelectionChange(realList) {
      if (!this.addFlag) {  //编辑
        this.addOrDel(this.oldList, realList)
        this.oldList = realList  // 保存table组件的选中数据,比真实选中数据少或一样
      } else { //新增
        this.tableSelectionList = realList
      }
      this.getSelectListInfo(this.tableSelectionList)
    },
    addOrDel(tempList, realList) {
      if (tempList.length < realList.length) {  // 选中
        this.tableSelectionList = this.noRepect([...realList, ...this.tableSelectionList])
      } else if (tempList.length > realList.length) {  // 取消选中
        // 差集--减少的数据
        let delList = tempList.filter(val => {
          let comId = val.comId
          return realList.every(v => v.comId != comId);
        })
        // 差集--实际数据
        this.tableSelectionList = this.tableSelectionList.filter(val => {
          let comId = val.comId
          return delList.every(v => v.comId != comId);
        })
      }
    },
    noRepect(list) { //去重
      let hash = {}
      return list.reduce((preVal, curVal) => {
        hash[curVal.comId] ? '' : hash[curVal.comId] = true && preVal.push(curVal)
        return preVal
      }, [])
    },

这样就圆满解决了


后续优化

做完上面一通操作后,回过头想想
这数据操作太麻烦了吧,应该有更好操作的方法吧
看到官方文档给出

事件名说明参数
select当用户手动勾选数据行的 Checkbox 时触发的事件selection, row
select-all当用户手动勾选全选 Checkbox 时触发的事件selection

这不就很好用嘛

<el-table :data="listInfo.dataList" border stripe v-loading="listInfo.listLoading" height="600px"
 @select="handSelect" @select-all="selectAll" :row-key="getRowKeys" ref="multipleTable">
   <el-table-column type="selection" align="center" width="50"></el-table-column>
   ......
</el-table>
	// 单选
    handSelect(selection, row) {
      let index = this.tableSelectionList.findIndex(item => row.comId === item.comId)
      if (index != -1) {
        this.tableSelectionList.splice(index, 1)
      } else {
        this.tableSelectionList.push(row)
      }
      this.getSelectListInfo(this.tableSelectionList)
    },
    //全选
    selectAll(selection) {
      // 把当前页数据过滤
      let tempList = this.tableSelectionList.filter(res => this.listInfo.dataList.findIndex(item => res.comId === item.comId) == -1)
      if (selection.length == 0) {  // 全不选
        this.tableSelectionList = tempList
      } else {  // 全选
        this.tableSelectionList = [...tempList, ...this.listInfo.dataList]
      }
      this.getSelectListInfo(this.tableSelectionList)
    },

搞定,简单易懂


结尾

重要的事情再说三遍:看文档!看文档!看文档!
当时写的时候没看文档,浪费时间写了一大堆,wwwww
(PS: 真就是隔几个月看再看看自己写的代码,哪个辣鸡写的💩。再看上一次修改人,哦,原来是我啊🤡🤡🤡)

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在使用 element-plus 的 el-table 进行多选时,可以通过绑定一个对象来实现数据回显。具体实现方法如下: 1. 在获取表格数据时,将数据转化为一个以 id 为键,整个数据对象为值的字典对象。 2. 在获取回显数据时,将数据转化为一个以 deviceId 为键,整个数据对象为值的字典对象。 3. 在 el-table 的 @select 事件,将选的数据对象存入回显数据字典对象。 4. 在 el-table 的 @select-all 事件,遍历所有数据对象,将其存入回显数据字典对象。 5. 在 el-table 的 :row-selected 事件,根据回显数据字典对象是否存在当前数据对象的 id 或 deviceId,来判断当前数据对象是否应该被选。 具体代码实现可以参考以下示例: ``` <template> <el-table ref="tableRef" :data="tableData" @select="handleSelect" @select-all="handleSelectAll" :row-selected="isRowSelected" row-key="id" > <el-table-column type="selection" width="55" /> <el-table-column type="index" label="序号" width="150" /> <el-table-column prop="name" label="电厂名称" /> </el-table> </template> <script> export default { data() { return { tableData: [], // 表格数据 selectedData: {}, // 回显数据 } }, methods: { // 获取表格数据 async fetchData() { const res = await fetchTableData() this.tableData = res.data.reduce((dic, item) => { dic[item.id] = item return dic }, {}) }, // 获取回显数据 async fetchSelectedData() { const res = await fetchSelectedData() this.selectedData = res.data.reduce((dic, item) => { dic[item.deviceId] = item return dic }, {}) }, // 处理单个选事件 handleSelect(selection, row) { this.$set(this.selectedData, row.deviceId, row) }, // 处理全选事件 handleSelectAll(selection) { Object.values(this.tableData).forEach(row => { this.$set(this.selectedData, row.deviceId, row) }) }, // 判断行是否被选 isRowSelected(row) { return !!this.selectedData[row.id || row.deviceId] }, }, mounted() { this.fetchData() this.fetchSelectedData() }, } </script> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值