饿了么框架做可编辑表格时想优化体验做个方向键操控,
网上搜到的代码不太满意,自己写了个
/**
* 键盘移动工具类,使用方法如下
* <pre>
* <template slot-scope="scope">
* <el-input v-model="scope.row.valuesScore"
* v-bind:ref="'r'+ scope.$index + 'c' + 1"
* @keydown.native="keyup($event, scope.$index, 1)"></el-input>
* </template>
*
* import {tableKeyMove} from "../util/tableKeyMove"
*
* keyup(ev, row, col) {
* tableKeyMove(this, ev, row, col, this.tableData.length, 6)
* },
* </pre>
*/
export function tableKeyMove(_this, ev, row, col, rowCount, colCount) {
// 替代 switch 的优雅写法
const actions = {
'ArrowUp': () => {
row--
if (row < 0) row = rowCount - 1
},
'ArrowDown': () => {
row++
if (row >= rowCount) row = 0;
},
'ArrowLeft': () => {
if (ev.target.selectionEnd !== 0) {
return
}
col--
if (col < 1) col = colCount;
},
'ArrowRight': () => {
if (ev.target.selectionEnd !== ev.target.value.length) {
return
}
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()
})
}
}












网友评论