饿了么框架做可编辑表格时想优化体验做个方向键操控, 网上搜到的代码不太满意,自己写了个
<el-table-column v-bind:label="'标题'" prop="valuesScore" sortable>
<template slot-scope="scope">
<el-input v-model="scope.row.valuesScore"
v-bind:ref="'r'+ scope.$index + 'c' + 1"
@input='input(scope.row, scope.row.valuesScore, range.value)'
@keyup.native="keyup($event, scope.$index, 1)"
@change='save(scope.row)'></el-input>
</template>
</el-table-column>
// region [键盘操作]
keyup(ev, row, col) {
this.keyupTo(ev, row, col, this.tabledatas.length, 6)
},
keyupTo(ev, row, col, rowCount, colCount) {
// 替代 switch 的优雅写法
const actions = {
'ArrowUp': () => {
row--
if (row < 0) row = rowCount - 1
},
'ArrowDown': () => {
row++
if (row >= rowCount) row = 0;
},
'ArrowLeft': () => {
col--
if (col < 1) col = colCount;
},
'ArrowRight': () => {
col++
if (col > colCount) col = 1
},
'Enter': () => {
col++
if (col > colCount) {
// 右下角的话保持不动
if (row === (rowCount - 1)) {
col = colCount
} else {
col = 1
row++
}
}
},
}
let action = actions[ev.key];
if (action !== undefined) {
action.call()
// 用 nextTick 避免 input 还没渲染出来
this.$nextTick(() => {
this.$refs['r' + row + 'c' + col].focus()
})
}
},
// endregion 键盘操作