返回

剖析 Element UI 表格复选框的默认选中、禁用及锁定状态

前端

使用 Element UI 的复选框打造灵动的表格交互

默认选中状态

Element UI 的复选框支持默认选中状态,让你的表格在加载时自动勾选指定行。首先,为 <el-table-column> 赋予 type="selection" 属性。其次,在数据源中,为需要默认选中的行设置 selected 字段为 true。通过这种方式,你可以快速标记出关键数据,无需用户手动操作。

<el-table-column type="selection" width="55">
  <template slot-scope="scope">
    <el-checkbox v-model="scope.row.selected"></el-checkbox>
  </template>
</el-table-column>
// 数据源示例
const data = [
  { id: 1, name: 'John Doe', selected: true },
  // ...
];

禁用状态

有时,你可能需要禁用特定行的选择功能。Element UI 的复选框提供了 disabled 属性,让你轻松实现这一需求。只需在 <el-checkbox> 中添加此属性,并将其绑定到数据源中行的 disabled 字段即可。如此一来,用户将无法勾选已禁用的行。

<el-table-column type="selection" width="55">
  <template slot-scope="scope">
    <el-checkbox v-model="scope.row.selected" :disabled="scope.row.disabled"></el-checkbox>
  </template>
</el-table-column>
// 数据源示例
const data = [
  { id: 1, name: 'John Doe', selected: true },
  { id: 2, name: 'Jane Smith', disabled: true },
  // ...
];

默认选中不可取消状态

为了确保某些关键数据始终被选中,Element UI 提供了默认选中不可取消状态。该状态允许你在表格加载时自动勾选某些行,同时禁止用户取消选中这些行。通过同时设置 selectedreserve-selection 属性,你可以实现这一功能。

<el-table-column type="selection" width="55">
  <template slot-scope="scope">
    <el-checkbox v-model="scope.row.selected" :reserve-selection="scope.row.reserve"></el-checkbox>
  </template>
</el-table-column>
// 数据源示例
const data = [
  { id: 1, name: 'John Doe', selected: true, reserve: true },
  // ...
];

活用复选框,构建灵活表格

Element UI 的复选框提供了多种状态选项,让你可以根据自己的需求定制表格交互。通过默认选中、禁用和默认选中不可取消状态,你可以创建更直观、高效的表格应用。

常见问题解答

  1. 如何判断一行是否被选中?

    • 通过访问行的 selected 字段,你可以检查该行是否被选中。
  2. 如何禁用所有行选择?

    • <el-table> 中设置 disable-row-selection="true" 属性。
  3. 如何获取选中的行数据?

    • 使用 $refs 访问表格实例,然后调用 getSelectedRows() 方法。
  4. 如何仅保留选定的行?

    • 调用 toggleRowSelection() 方法,将 selection 参数设置为 true,并将 clear 参数设置为 true
  5. 如何处理复选框点击事件?

    • 可以在 <el-checkbox> 中添加一个 @click 事件处理程序,以便在单击复选框时执行特定的操作。