0
点赞
收藏
分享

微信扫一扫

ElementUI el-table 多选以及点击某一行的任意位置就勾选上

海滨公园 2024-11-06 阅读 37

1. 需求

在el-table中,需要实现多选功能,并且点击某一行的任意位置就勾选上,而不是点击复选框才勾选上。

2. 实现思路

  1. 在el-table中添加ref属性,用于获取表格实例。
  2. 在el-table-column中添加type="selection"属性,用于显示复选框。
  3. 在el-table中添加@row-click="handleRowClick"属性,用于点击某一行的任意位置就获取到。
  4. 在handleRowClick方法中,通过toggleRowSelection方法来勾选或取消勾选当前行。

3. 代码实现

<template>
  <el-table
    ref="tableRef"
    :data="tableData"
    @selection-change="handleSelectionChange"
    @row-click="handleRowClick"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="date" label="日期" width="180"></el-table-column>
    <el-table-column prop="name" label="姓名" width="180"></el-table-column>
    <el-table-column prop="address" label="地址"></el-table-column>
  </el-table>
</template>

<script>
import { ref, reactive } from 'vue'
const tableRef = ref(); // 获取表格实例
const state = reactive({
    tableSelections: [] as any[],
})
/**
 * 表格,多选
 */
const handleSelectionChange = (val: any) => {
    state.tableSelections = val
    // console.log(val, '---val')
}
<!--  -->
function handleRowClick(row: any) {
  // 判断当前行是否被选中
    const isSelected = state.tableSelections.includes(row);
  // 如果当前行被选中,则取消选中;如果当前行未被选中,则选中
    tableRef.value?.toggleRowSelection(row, !isSelected);
}
</script>
举报

相关推荐

0 条评论