element Table使用toggleRowSelection添加默认值不生效的原因与解决方法

我遇到的需求,多选列表中的数据回显到页面中的表格,页面中的表格可以删除数据。

点击图片一中的选择按钮弹出图片2的弹框
在这里插入图片描述
图片2中选中的数据回显到图片一的表格
在这里插入图片描述

每次切换页码或者打开弹窗都需要匹配上已选中的数据,所以就需要用到
this.$refs[你表格绑定的ref].toggleRowSelection()

this.$refs[你表格绑定的ref].clearSelection()

我下面的代码是每次请求接口后就去循环已选中列表,通过toggleRowSelection方法给弹框中(图片2)的表格添加已选中

apis
  .merListApi(params)
  .then(res => {
    
    
    this.isLoading = false;
    this.merList = res.data.list;
    this.pagination = res.data.pagination;
    this.$nextTick(() => {
    
    
      this.$refs.multipleTable.clearSelection();
      this.form.merchant_list.forEach(val => {
    
     // this.form.merchant_list 是我已选中的数据列表
        this.$refs.multipleTable.toggleRowSelection(val, true);
      })
    })
  })
  .catch(() => {
    
    
    this.isLoading = false;
  });

很遗憾,不得行,经过仔细对比,但是我感觉我的代码和官方文档使用没有啥区别,我又想到是不是我element的版本等级过低?我马上yarn add 了一下element的最新依赖,结果还是不得行。

我有怀疑官方文档的代码是否好使?我就把他的代码复制过来试一下,居然好使,然后我再仔细对比,发现只有一点不一样:我是两个表格的数据,而官方toggleRowSelection操作的同一个表格的数据,我们之间的差别就是数组之间的指针,然后我根据这一点修改代码
apis
  .merListApi(params)
  .then(res => {
    
    
    this.isLoading = false;
    this.merList = res.data.list;
    this.pagination = res.data.pagination;
    this.$nextTick(() => {
    
    
      try {
    
    
        this.$refs.multipleTable.clearSelection();
        this.form.merchant_list.forEach(val => {
    
    
          this.$refs.multipleTable.toggleRowSelection(
            this.merList.find( // 这是我弹框表格的数据
              item => val.merchant_id === item.merchant_id
            ),
            true
          )
        })
      } catch (error) {
    
    }
    })
  })
  .catch(() => {
    
    
    this.isLoading = false;
  })

通过find方法,让弹框中的list(this.merList)去匹配已选中list(this.form.merchant_list)的数据,然后使用toggleRowSelection,这一次终于成功了,总结:toggleRowSelection操作的数据和指针有关,我们只能操作当前列表的list,就像之前我的错误操作,虽然toggleRowSelection传入的row(val)和选中列表中的某一项数据一模一样,但是我传入的row和弹框列表某一项的row指向不同的地址

猜你喜欢

转载自blog.csdn.net/weixin_44441196/article/details/117744491#comments_26964507