> 技术文档 > 【element ui系列】分享几种实现el-table表格单选的方法_el-table 单选

【element ui系列】分享几种实现el-table表格单选的方法_el-table 单选

在实际的开发中,经常会用到从表格中选择一条记录的情况,虽然官方给出的例子,但是给人感觉看起来不明显,于是,在此基础上做了改进。接下来,介绍两种常见的实现方法:

1、采用复选框(checkbox)实现,去掉表头多选框,代码如下:

 
{{ scope.row.date }}
export default { data() { return { tableData: [{ id: \'1\', date: \'2016-05-03\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'2\', date: \'2016-05-02\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'3\', date: \'2016-05-04\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'4\', date: \'2016-05-01\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'5\', date: \'2016-05-08\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'6\', date: \'2016-05-06\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'7\', date: \'2016-05-07\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }], selectList: [] } }, methods: { toggleSelection(rows) { if (rows) { rows.forEach(row => { this.$refs.multipleTable.toggleRowSelection(row); }); } else { this.$refs.multipleTable.clearSelection(); } }, handleSelectionChange(val) { this.selectList = val; // 单选 if (val.length > 1 ) { this.$refs.multipleTable.clearSelection(); this.$refs.multipleTable.toggleRowSelection(val.pop()); } }, // 点击一行时选中 clickRow(row){ // 单选选中行 if (this.selectList[0] == row) { // 取消 this.selectList = []; this.$refs.multipleTable.clearSelection(); } else { // 选择 this.selectList = [row]; this.$refs.multipleTable.clearSelection(); this.$refs.multipleTable.toggleRowSelection(row, true); } }, } }/* 将全选项隐藏 */.section-table thead .el-table-column--selection .cell { display: none;}

效果如图:

2、采用单选框(radio),双击取消选中

 
{{\"\"}}
export default { data() { return { tableData: [{ id: \'1\', date: \'2016-05-03\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'2\', date: \'2016-05-02\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'3\', date: \'2016-05-04\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'4\', date: \'2016-05-01\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'5\', date: \'2016-05-08\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'6\', date: \'2016-05-06\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }, { id: \'7\', date: \'2016-05-07\', name: \'王小虎\', address: \'上海市普陀区金沙江路 1518 弄\' }], currentRow: null } }, methods: { setCurrent(row) { this.$refs.singleTable.setCurrentRow(row); }, handleCurrentChange(row) { this.currentRow = row; }, rowClick2(row, column, event) { if (this.currentRow && row.date == this.currentRow.date) { this.setCurrent(); this.currentRow = null; } else { this.currentRow = row; } }, } }/* 将radio的label隐藏 */.el-radio__label{ display: none !important; }

效果如下图: