字节笔记本字节笔记本

Vue3 Element Plus Table Selection 回显多选项

2022-07-15

Vue3 Element Plus Table实现多选回显功能,通过设置`reserve-selection`属性为`true`并使用`toggleRowSelection`方法根据ID回显选中状态。

 <ElTable
        ref="TableRef"
        :columns="columns"
        :data="tableData"
        :row-key="(row) => { return row.id }"
        max-height="300px"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :reserve-selection="true" type="selection" width="55" />
        
  • :row-key="(row) => { return row.id }" 返回row的唯一id
  • column type 为 selection的 column 添加回显属性``:reserve-selection="true"`
const refreshTableSelection = async () => {
  const ids = props.modelValue?.map(user => user.id) ?? []
  await nextTick(() => {
    if (TableRef.value) {
      for (let i = 0; i < tableData.value.length; i++) {
        if (ids.includes(tableData.value[i].id))
          (TableRef.value as TableInstance).toggleRowSelection(tableData.value[i], true)
        else
          (TableRef.value as TableInstance).toggleRowSelection(tableData.value[i], false)
      }
    }
  })
}