最近在项目中客户要求在表格选择时,可以按住shift键来实现类似excel的多选功能。
下面直接进入代码:
- 首先需要在表格挂载完成后绑定键盘事件:
mounted () {
window.addEventListener('keydown', e => {
if (e.keyCode === 16 && e.shiftKey) {
this.keepDown = true;
}
});
window.addEventListener('keyup', e => {
this.keepDown = false;
});
},
- 接着利用table组件的select事件
data () {
return {
startIndex: -1, // 选择起始行索引
keepDown: false, // 是否按住shift键
}
}
methods: {
shiftMultiple (selection, row) {
const data = this.$refs.tableRef.tableData; // 获取table当前数据
const startIdx = this.startIndex; // 获取首次选择对应列的索引
const endIdx = row.index; // 获取最后选择的索引
if (this.keepDown && selection.includes(data[startIdx])) {
const sum = Math.abs(startIdx - endIdx) + 1; // 用户可能反向选取,所以要取绝对值
const min = Math.min(startIdx, endIdx); // 获取起点和终点较小的值
let i = 0;
while (i < sum) {
const index = min + i;
if (!this.selectRows.includes(data[index])) {
this.selectRows.push(data[index]);
this.selectRowIds.push(data[index].id);
this.$refs.tableRef.toggleRowSelection(data[index], true);
}
i++;
}
} else {
this.startIndex = row.index; // 记录最后一次仅点击的索引
}
}
}
- 模板:
<el-table ref="tableRef" :data="tableData" border @select="shiftMultiple">
注:列表项的索引是在数据请求回来后自信添加的,当表格重新排序后需重新赋值索引,否则上述功能会乱序