element-UI实现table表格单选及单选点击取消选中

如果你想实现在一个表格中,有个单选的选项,点击可以选中某一行的数据,再次点击也可以取消勾选,那下面这个方法可以满足你的需求。

网上很多方法使用都不行,多多少少都有点问题,参照别人的写了一份,自测没有问题,代码你可以再精简一下,我这里就不优化了,如果你遇到这样的需求,请看下面的代码。

效果图:点击选中—再次点击取消选中
在这里插入图片描述

<el-table
   v-loading="loadingg"
    :data="tableData" height="100%"
    style="width: 100%"
    :highlight-current-row="true"
    @current-change="clickChange">
    <el-table-column
      label="选择"
      width="50px">
      <template slot-scope="scope">
        <el-radio
            :label="scope.row.id"
            v-model="selectRadio"
            @click.native.stop.prevent="getCurrentRow(scope.row)"
          >&nbsp;</el-radio>
      </template>
    </el-table-column>

    <el-table-column
      prop="name"
      label="名称"  >
    </el-table-column >
 </el-table>

注意:@click.native.stop.prevent,一定要加上这些修饰符,不然点击的话会触发2次,勾选就不生效了。

data () {
  return {
     loading: false,
     tableData: [],
     selectRadio: '',
     forbidden: true
   }
 },
 // 单选
 getCurrentRow (row) {
    if (!this.forbidden) {
      this.forbidden = true
    }
    if (this.selectRadio) {
      if (this.selectRadio === row.id) {
        this.selectRadio = ''
        this.forbidden = false
        setTimeout(() => {
          this.forbidden = true
        }, 0)
        this.$emit('changeData', {}) // 取消勾选就把回传数据清除
        return
      } else {
        this.forbidden = false
        setTimeout(() => {
          this.forbidden = true
        }, 0)
      }
    } else {
      this.forbidden = false
      setTimeout(() => {
        this.forbidden = true
      }, 0)
    }
    this.selectRadio = row.id
    this.$emit('changeData', row)
  }

changeData是向父组件回传的数据

如果编辑时实现从父组件进来,默认选中某个数据的话,可以通过props传值,给selectRadio赋值就行了

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值