按键切换input


1:、需求:用户在处理大量数据表格的时候用鼠标一个个点很麻烦,于是想要按键移动编辑改完按方向键移动编辑下一个

2、思路:简单来说就是利用input的blur()和focus()方法,我这里用了element组件,原生也差不多,按键的时候focus下一个要移动的dom,blur之前的dom,就可以完成input之间的切换(在处理大量数据生成多个dom的时候如何优化将是个大问题,表格会卡死,设置可视区间才渲染dom等等方法是个不错的优化方向)

3、实现

3-1、绑定虚拟dom

                               

3-2、触发方法

        leftFocus(rowIndex, colIndex) {
            console.log(rowIndex, colIndex)
            if (rowIndex && (colIndex || colIndex === 0)) {
                this.$refs.saleOrderTable.doLayout()
                const nextInput = document.getElementById(`cellinput-${rowIndex - 1}-${colIndex}`)
                console.log(nextInput)
                console.log(nextInput.focus)
                if (nextInput) {
                    nextInput.focus();
                    const curInput = document.getElementById(`cellinput-${rowIndex}-${colIndex}`)
                    curInput.blur();
                } else {
                    const scrollDom = this.$refs.addTable.bodyWrapper;
                    if (scrollDom && scrollDom.scrollLeft) {
                        console.log(scrollDom);
                        scrollDom.scrollLeft = 0;
                    }
                }
            }
        },
        rightFocus(rowIndex, colIndex) {
            if (rowIndex && (colIndex || colIndex === 0)) {
                const nextInput = document.getElementById(`cellinput-${rowIndex + 1}-${colIndex}`)
                if (nextInput) {
                    nextInput.focus();
                    const curInput = document.getElementById(`cellinput-${rowIndex}-${colIndex}`)
                    curInput.blur();
                }
            }
        },
        upFocus(rowIndex, colIndex) {
            if (rowIndex && (colIndex || colIndex === 0)) {
                const nextInput = document.getElementById(`cellinput-${rowIndex}-${colIndex - 1}`)
                if (nextInput) {
                    nextInput.focus();
                }
            }
        },
        downFocus(rowIndex, colIndex, isOverAdd) {
            if (rowIndex && (colIndex || colIndex === 0)) {
                const nextInput = document.getElementById(`cellinput-${rowIndex}-${colIndex + 1}`)
                if (nextInput) {
                    nextInput.focus();
                } else if (!isOverAdd) {
                    this.$message({
                        message: "已在最后页数添加空行!",
                        type: "success",
                    });
                    this.form.saleOrderItems.push(
                        Object.assign({}, this.saleOrderItemModel)
                    );
                    this.frontFormInline.total = this.form.saleOrderItems.length;
                    this.query();
                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.downFocus(rowIndex, colIndex, true);
                        }, 0);
                    });
                }
            }
        },

4、效果