Vue3: The el-table multi-selection box is selected by default, and the page is turned to keep the selected state

Problem: The el-table multi-selection box is selected by default, and the page is turned. The previously selected data does not remain selected.

   <template>
    <el-table
      style="width: 100%"
      border
      :data="state.usersData"
      @selection-change="userSelectionChange"
      ref="multipleTable"
      :row-key="getRowKeys"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true" />
      <el-table-column property="nickName" label="用户名" />
      <el-table-column property="name" label="姓名"  />
      <el-table-column property="mobile" label="手机号"/>
      <el-table-column property="email" label="邮箱"/>
    </el-table>
    <el-pagination
      :current-page="state.paramData.page"
      :page-size="state.paramData.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :background="true"
      :total="state.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </template>
    <script setup>
const state=reactive({
    
    
   tableData:[],
   selectedData:[],
   paramData:{
    
    
     page:1,
     pageSize:10
      },
    total:0
    })
    //获取表格数据
const getMessage=async ()=>{
    
    
         const {
    
    data}=await getUsers();
         state.tableData=data;
    }
    //用户数据反显(默认选中)
const multipleTable = ref();
const reserveSelection = () => {
    
    
  if (selectData.value.length !== 0) {
    
    
    selectData.value.forEach((item) => {
    
    
      setTimeout(() => {
    
    
        multipleTable.value.toggleRowSelection(item, true); //让页面显示选中的数据
      }, 0);
    });
  }
};
//指定key值,数据更新之后保留之前选中的数据
const getRowKeys = (row) => {
    
    
  return row.userId;
};

const handleCurrentChange = (val) => {
    
    
  state.paramData.page = val;
};
const handleSizeChange = (val) => {
    
    
  state.paramData.pageSize = val;
};
const userSelectionChange = (values) => {
    
    
  state.selectedData = [...values];
};
        
    </script>

Summary steps:
1. Add: row-key="getRowKeys" to the el-table tag
2. Add type="selection" and :reserve-selection="true" to the first row in el-table-column
3. Use the toggleRowSelection method in el-table, where the second parameter of the method is set to true to select

Note : When using the toggleRowSelection method, it must be performed in an asynchronous operation (setTimeout or nextTick), because when the data changes, vue's dependency monitoring and view update process is performed asynchronously , so the view update task is still waiting at this time. It is invalid to manipulate dom through ref

Guess you like

Origin blog.csdn.net/CYL_2021/article/details/130194387