问题:
一个el-table表格里面每一个框框都是一个el-input 然后给输入框v-model绑定值,绑定完成之后我们会发现有这么一个问题,不能按住上下左右键盘来移动,这时候我们操作就来了,效果如下:
步骤走起:代码不做解释,开发时间久了就懂了
import { nextTick } from 'vue'
export class DirectionKey {
constructor(str, code) {
let _that = this
str.split('_').forEach(item => {
let o = item.split('=')
_that[o[0]] = o[1]
})
if (code === 38) {
this.previousLine()
}
if (code === 40) {
this.nextLine()
}
if (code === 39) {
this.next()
}
if (code === 37) {
this.previous()
}
}
next(x = this.x, y = this.y) {
this.move({ x: ++x, y })
}
previous(x = this.x, y = this.y) {
this.move({ x: --x, y })
}
nextLine(x = this.x, y = this.y) {
this.move({ x, y: ++y })
}
previousLine(x = this.x, y = this.y) {
this.move({ x, y: --y })
}
move({ x, y }) {
nextTick(() => {
let el = document.getElementById(`x=${x}_y=${y}`)
el && el.focus()
})
}
}
我这个是放在util文件里面的一个单独js文件, @/util/direction.js
接着我们就给el-table 设置一个按下事件
<el-table :data="xxx" border @keydown="keymove">
<el-table-column></el-table-column> <!--里面的反正都是一个el-input就对了-->
</el-table>
然后呢给每一个el-input绑定成这样子的id,注意:如果你的el-table-column是循环的中间的index就改成你循环的那个index,如果是一个个手写的话就从0依次到结束 :id="'x=' +0+ '_y=' + $index"
<el-input
v-else :id="'x=' + index + '_y=' + $index"
v-model="row.xxx"
clearable
size="small"/>
接下来就直接在script里面声明一个方法,方法如下:
// 上下左右箭头移动
function keymove(e) {
if (e.key.substring(0, 5) !== 'Arrow') return
e.preventDefault()
new DirectionKey(e.target.id, e.keyCode)
}
就没有然后啦,大概效果就是这样子