很多公司官网的登陆页面都有这样的需求,当用户输入完用户名之后,按键盘的Enter键就可以切换到下一行的密码输入框,并将光标聚焦到密码框这一行,聚焦这个功能主要通过触发input框的focus事件来实现
一、密码框聚焦(确定ref值)
我们给密码框增加ref属性为passwordInput,监听用户名输入框的Enter事件,增加下列代码,即可聚焦到密码框
this.$refs.passwordInput.focus();
二、使用v-for为每一个Input动态添加ref
现在我们的需求变了,不再是确定的ref值,当按Enter键时,增加一个input框,并聚焦到新增的input框
【1】数组列表
data() {
return {
questionList: [
{ question: "" }
],
};
},
【2】v-for循环数组列表,为每一项动态添加ref
<div v-for="(item, index) in questionList" :key="index">
<Input v-model="item.question" :ref="`question`" @keyup.enter.native="addRow(index)" />
</div>
【3】Enter事件
数组列表增加一行,并聚焦到该行
methods: {
addRow(index) {
// 增加行
let obj = { question: "" };
this.quesionList.splice(index + 1, 0, obj);
// 聚焦
this.$nextTick(() => {
this.$refs.question[index + 1].focus();
});
}
}
【4】效果
文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料