element-ui 带单选框的表格

效果:不只是带单选框,点击当前行单选框选中状态
网上查了一些发现很多都是只能点击当前radio选中当前行,配合element-ui的单选table时发现两个的选择状态是不一致的,所以调整了一下
效果

提供下思路:

1.保证不止是点击单选框,点击列表某行也能够选中,通过设置highlight-current-row和@current-change="handleCurrentChange"实现

2.radio为单选框的值,选中后为当前行数,翻页后为保证重新选中状态需要重制

3.我的项目里需求是组件化形式,单选框选中值传递给父组件,父组件可能会有默认数据传入,需要在打开时设置点选状态

部门关键代码

<template>
  <el-table
    :data="tableData"
    ref="orderTable"
    @current-change="handleCurrentChange"
    tooltip-effect="light"
    highlight-current-row
    :cell-style="cellStyle"
   >

<!--

&nbsp; 为空,不加这个radio的label会显示index数字,注意从0开始的;radio会全选的问题是label相同导致的
disabled设置单选框是否可以被选择 -->
    <el-table-column label="选择" width="50" center>       <template slot-scope="scope">         <el-radio           class="radio"           v-model="radio"           :label="scope.$index"           @change.native="getCurrentRow(scope.$index)"           :disabled="scope.row.Enable==1?false:true">         &nbsp;</el-radio>       </template>     </el-table-column>   </el-table>     <el-pagination     background     layout="total, prev, pager, next"     :current-page.sync="pagination.pageNum"     :page-size="pagination.pageSize"     :total="pagination.total"     @current-change="changePage"     :pager-count="5"    ></el-pagination> </template> <script> export default {   data() {     return {       currentRow: null,       radio: false,       tableData: [],   },
  porps:{
    //父组件传递过来的初始选中值,根据自己项目需求设置
    chooseData:{
      type:Object
    }
  },
  watch:{
    //观察是否有父组件传递的初始值或者变化,重新选中
    chooseData(val){
      if(val){
        this.radio = false
        this.getInitChoose()
      }
    }
  },   methods:{           getList() {         this.isListLoading = true;           getTableData().then(res => {             this.tableData = res.item;              //每次数据改变重新判断单选状态             this.getInitChoose();           })       },       //设置单选框选择状态       getInitChoose() {         if (this.chooseData) {           let index = this.tableData.findIndex(           item => item.userUuid == this.chooseData.id         );         if (index > -1) {           this.radio = index;         }       },       //由于翻页后重新获取列表了,需要把选择框选中状态取消       changePage(pageNum) {         this.pagination.pageNum = pageNum;         this.radio = false         this.getList()       }, /* current-change 当表格的当前行发生变化的时候会触发该事件,如果要高亮当前行,请打开表格的 highlight-current-row 属性 currentRow, oldCurrentRow */ //保证点击当前行的任意位置不止是单选框也能够选择       handleCurrentChange(val) {         if (val && val.Enable == 1) {           this.currentRow = val;           let index = this.tableData.findIndex(           item => item.userUuid == this.currentRow.userUuid         )         if (index > -1) {           this.radio = index;         }         this.$emit('data',val.pkg)       },       getCurrentRow(index) {         this.radio = index          },    } } </script>
原文地址:https://www.cnblogs.com/calamus/p/8569196.html