友友们,就直接上代码了哇
第一步:在需要的地方设置键盘事件:、
<avue-crud
@keydown="handleFocus"
@cell-click="handleCellClick"
>
</avue-crud>
第二步:在生命周期(钩子函数)
created() {
document.addEventListener('keyup', this.handleKeyup)
},
// 同一级别
destroyed() {
// 移除键盘按键事件监听
document.removeEventListener('keyup', this.handleKeyup)
},
第三步:写判断条件和逻辑
handleCellClick(row, column, cell, event) {
this.currentIndex = this.infodata.indexOf(row)
this.currentCol = column.property
},
//键盘事件
handleKeyup(event) {
if (event.keyCode === 38 && this.currentIndex > 0) {
// 处理上箭头按键
this.currentIndex--;
this.$nextTick(() => {
this.handleFocus();
});
} else if (event.keyCode === 40 && this.currentIndex < this.infodata.length - 1) {
// 处理下箭头按键
this.currentIndex++;
this.$nextTick(() => {
this.handleFocus();
});
} else if (event.keyCode === 37 && this.currentIndex >= 0) {
// 处理左箭头按键
this.handleLeftArrow();
} else if (event.keyCode === 39 && this.currentIndex >= 0) {
// 处理右箭头按键
this.handleRightArrow();
} else if (event.keyCode === 13) {
// 处理回车键
this.handleEnterKey();
}
},
handleRightArrow() {
// 处理右箭头按键
if (this.currentIndex >= 0) {
const currentRow = this.$refs.infoCrud.$el.querySelectorAll('.el-table__body-wrapper > table > tbody > tr')[this.currentIndex]; // 当前行元素
const inputsInCurrentRow = currentRow.querySelectorAll('td input'); // 当前行所有的 input 元素
const focusedInput = document.activeElement; // 获取当前获得焦点的元素
let nextInputIndex = Array.from(inputsInCurrentRow).findIndex(input => input === focusedInput) + 1; // 下一个输入框的索引
if (nextInputIndex < inputsInCurrentRow.length) {
inputsInCurrentRow[nextInputIndex].focus(); // 聚焦到下一个输入框
}
}
},
handleLeftArrow() {
// 处理左箭头按键
if (this.currentIndex >= 0) {
// 处理左箭头按键
const currentRow = this.$refs.infoCrud.$el.querySelectorAll('.el-table__body-wrapper > table > tbody > tr')[ this.currentIndex]; // 当前行元素
const inputsInCurrentRow = currentRow.querySelectorAll('td input'); // 当前行所有的 input 元素
const focusedInput = document.activeElement; // 获取当前获得焦点的元素
let prevInputIndex = Array.from(inputsInCurrentRow).findIndex(input => input === focusedInput) - 1; // 上一个输入框的索引
if (prevInputIndex >= 0) {
inputsInCurrentRow[prevInputIndex].focus(); // 聚焦到上一个输入框
}
}
},
handleFocus() {
// 获取下一行的DOM元素
const nextRow = this.$refs.infoCrud.$el.querySelectorAll('.el-table__body-wrapper > table > tbody > tr')[this.currentIndex];
if (nextRow) {
// 找到下一行第6个td上的input元素并聚焦
const input = nextRow.querySelectorAll('td')[1].querySelector('input');
if (input) {
input.focus();
}
}
},
handleEnterKey() {
this.add()
},