vue中自动跳转input框,focus为跳转
时间: 2023-10-25 19:03:15 浏览: 36
在Vue中实现自动跳转到input框可以使用`ref`来引用input元素,并结合`focus`方法来设置焦点。下面是一个示例:
```html
<template>
<div>
<input ref="input1" @keyup.enter="gotoNextInput">
<input ref="input2" @keyup.enter="gotoNextInput">
<input ref="input3" @keyup.enter="gotoNextInput">
</div>
</template>
<script>
export default {
methods: {
gotoNextInput(e) {
const currentInput = e.target; // 获取当前输入框
const inputRefs = Object.keys(this.$refs).filter(ref => ref.startsWith("input")); // 获取所有input的引用
const currentIndex = inputRefs.indexOf(currentInput); // 获取当前输入框的索引
if (currentIndex < inputRefs.length - 1) {
const nextInput = this.$refs[inputRefs[currentIndex + 1]]; // 获取下一个输入框的引用
nextInput.focus(); // 设置焦点到下一个输入框
}
},
},
};
</script>
```
在模板中,我们使用`ref`为每个input元素指定一个引用,以便在Vue实例中引用它们。在`gotoNextInput`方法中,我们根据当前输入框的引用,找到下一个input的引用,并调用`focus`方法将焦点设置在下一个输入框上。当用户在一个输入框中按下"Enter"键时,会触发`keyup.enter`事件,从而调用`gotoNextInput`方法,实现自动跳转到下一个input框。