实现el-table两列多选框且不可同时勾选

文章描述了如何在Vue.js的表格组件中实现必修和选修课程的选择,确保两者不能同时被勾选。使用了el-table列和v-model双向数据绑定,以及自定义方法处理选中状态的互斥效果。

1、效果图如下,功能:必修和选修不可同时勾选
在这里插入图片描述
2、代码如下

<template>
      <el-table :data="addTableData" style="width: 100%">
        <el-table-column label="必修" width="55px" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="checked1" :label="scope.row.id" @change="checkboxChange($event,scope.row.id,'checked2')"><span></span></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="选修" width="55px" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="checked2" :label="scope.row.id" @change="checkboxChange($event,scope.row.id,'checked1')"><span></span></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="编号" width="60px" align="center"></el-table-column>
        <el-table-column prop="name" label="名称" align="center"></el-table-column>
        <el-table-column prop="name" label="学时" width="60px"  align="center"></el-table-column>
      </el-table>
</template>


  export default {
    data() {
      return {
        checked1:[],//必修已选
        checked2:[],//选修已选
      }
    }

    methods: {
      checkboxChange(val,id,type) {
        if(val === true) {
          this[type] = this[type].filter(function(item) {
            return item !== id;  // 过滤出值不为2的元素
          });
        }
      },
    }}
### element-ui `el-table` 分页多选框勾选回显解决方案 为了使 `el-table` 的分页功能支持多选框的状态回显,需设置特定属性并编写相应逻辑处理函数。 #### 设置表格配置项 在 `<el-table>` 组件中加入 `:row-key="record => record.id"` 属性来指定唯一键名作为每一行数据的身份标识符[^2]。这有助于框架识别不同页面间的相同记录条目,从而保持其选择状态不变。 ```html <el-table :data="tableData" border :header-cell-style="headClass" :row-style="{ height: '15px' }" style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTable" :row-key="record=>record.id" tooltip-effect="dark"> </el-table> ``` #### 配置多选列选项 对于包含多选框的第一列表格列定义部分,应增加 `:reserve-selection="true"` 参数以启用记忆上次已选中的项目特性: ```html <el-table-column type="selection" :reserve-selection="true" width="55"> </el-table-column> ``` #### 编写事件处理器 当用户改变当前所选行时触发 `@selection-change` 事件,并通过自定义的方法如 `handleSelectionChange(selection)` 来接收最新的被选中对象数组[^1]。此方法可用于更新内部存储的选择集合并同步至其他组件或服务端接口调用。 ```javascript methods: { handleSelectionChange(selection) { this.selectedRows = selection; console.log('Selected Rows:', JSON.stringify(this.selectedRows)); } } ``` 以上措施共同作用下可以有效解决 `el-table` 中由于翻页操作引起的选择丢失现象,确保用户体验流畅一致。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值