关于回显的处理element 中Table Methods 有一个方法
toggleRowSelection 用于多选表格,切换某一行的选中状态,如果使用了第二个参数,则是设置这一行选中与否(selected 为 true 则选中)

设置某一行选中
(这里是vue3)

table.value.toggleRowSelection(item)

设置某一行不选中

table.value.toggleRowSelection(item,false)

下面是完整代码

<template>
  <div class="list">
    <el-table ref="table"
              border
              height="228px"
              style="width:360px"
              :data="businessList"
              @selection-change="selectionChange"
              @select="select">
      <el-table-column type="selection"> </el-table-column>
      <el-table-column prop="name"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import { defineComponent, reactive, getCurrentInstance, ref, toRefs, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
  setup () {
    const { proxy } = getCurrentInstance()
    const store = useStore()
    const table = ref(null)
    const data = reactive({
      businessList: [],
    })

    onMounted(async () => {
		//获取表格的数据
        await getData()

      // 获取反显数据
      nextTick(() => {
      // 从vuex 里获取表格需要选中的行
        const obj = proxy.$store.state.warning
        try {
          obj.businessArr.forEach(item => {
            data.businessList.forEach(bus => {
              if (bus.id === item.id) {
                table.value.toggleRowSelection(bus)
              }
            })
          })
        } catch (e) {
        }
      })
    })

    // 请求表格数据
    const getDataApi = async (region_level, field) => {
      try {
        const res = await proxy.$api.getBusinessCitys({})
        if (!res.list) return proxy.$message.error(res.msg)
        data.businessList= res.list.list || []
      } catch (err) {
        proxy.$message.error(err)
      }
    }

    // 勾选checkbox时触发回调
    const select = (selection, row) => { }
     // 表格所选中的数据
    const selectionChange=()=>{}
    return {
      ...toRefs(data),
      table,
      getData,
      selectionChange,
      select
    }
  },
})
</script>
<style lang="scss" scoped>
</style>

这里需要注意的要做回显 toggleRowSelection方法传入的参数 必须是 el-table 绑定的数据
例如:

// 取出需要选中的数据 
  obj.businessArr=[
    {
       id: '1',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄',
      },
      {
        id: '2',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄',
      }]
      
      // table绑定的数据 
  data.businessList=[
	{
	  id: '1',
	    name: '王小虎',
	    address: '上海市普陀区金沙江路 1518 弄',
	  },
	  {
	   id: '2',
	    name: '王小虎',
	    address: '上海市普陀区金沙江路 1519 弄',
	  },
	  {
	   id: '3',
	    name: '王小虎',
	    address: '上海市普陀区金沙江路 1520 弄',
  }]
  
	//  回显处理
	for(let item of  obj.businessArr){
	//按要求传入数据
	  table.value.toggleRowSelection(item)  //此时执行了 但是表格并没有被选中
	}

这里的写法 表格并没有被选中的。 虽然你看着obj.businessArr的数据和data.businessList中的两个的数据是一样的,但是对象是按地址传递的,他们在内存中的地址不同,所以他们是两份不同的数据,所以这么写是不会回显选中的。

正确的写法就是上面的两次for循环,当id相同时把 data.businessList 中的item 传给toggleRowSelection

写在最后~~ 写的不好,有问题欢迎大家留言。

Logo

前往低代码交流专区

更多推荐