本小白在刚开始使用elementui表格,发现表格的行只能选中,不能直接在表格中取消选中行,所以在经过请教之后写出了一个方法,可以选中单元格,又可以取消选中。
<template>
<el-table ref="multipleTable" v-on:row-click="rowClick" :data="tableData" style="width: 100%">
<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>
在这个表格中,我们给表格定义了 ref 和表格的点击事件rowclick,接下来就用js去实现功能:
rowStyle: function ({ row, rowIndex }) {
Object.defineProperty(row, 'rowIndex', { value: rowIndex, writable: true, enumerable: false });
},
rowClick: function (row, column, event) {
let me = this;
if (!utils.isEmpty(this.selectData) && this.selectData.rowIndex == row.rowIndex) {
this.$refs.multipleTable.setCurrentRow();
this.selectData = null;
this.$refs.multipleTable.toggleRowSelection(row, false);
} else {
this.selectData = row;
this.$refs.multipleTable.toggleRowSelection(row, true);
}
},
在<script></script>的methods中写入上述方法,rowStyle方法是给每一行添加不可枚举属性rowIndex来标识当前行,再通过rowClick方法对当前行进行选中取消,则可实现表格的选中和取消选中功能。