简体   繁体   English

Vue:将焦点设置为动态输入框

[英]Vue: Set focus to dynamic input box

I have a form where user can fill an email address and click a plus button against it to create a new one.我有一个表单,用户可以在其中填写一个电子邮件地址,然后单击它旁边的加号按钮来创建一个新的。 These input boxes are generated by iterating over an array.这些输入框是通过迭代数组生成的。 When user clicks on the + icon, a new entry is pushed to this array.当用户点击 + 图标时,一个新条目被推送到这个数组。

Now the new text box is generating fine but I want the cursor to be focused in this one.现在新的文本框生成得很好,但我希望光标集中在这个文本框上。

在此处输入图片说明

as @ramakant-mishra told you must use this.$refs , but you need to add ref attribute dynamically on your input element also.正如@ramakant-mishra 告诉您必须使用this.$refs ,但您还需要在输入元素上动态添加 ref 属性。 let me show you:让我演示给你看:

 new Vue({ el: '#app', data: { emails:[] }, methods: { add: function (e) { let j = this.emails.push("") this.$nextTick(() => { this.$refs[`email${j - 1}`][0].focus() }) } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-for="(email, i) in emails" :key="i"> <input v-model="email" :ref="`email${i}`" /> </div> <button @click="add">add</button> </div>

just don't forget to use $nextTick because the new element is not rendered yet on template只是不要忘记使用 $nextTick 因为新元素尚未在模板上呈现

They key is to set ref on all your input s to the same string like this:他们的关键是将所有inputref设置为相同的字符串,如下所示:

<input type="text" ref="myInputs"/>

Then you will have access to an array called this.$refs.myInputs inside an event handler.然后,您将可以访问事件处理程序中名为this.$refs.myInputs的数组。

 new Vue({ el: "#app", data() { return { emails: [] }; }, methods: { addEmail() { this.emails.push('whatever'); this.$nextTick(() => { const lastIdx = this.emails.length - 1; this.$refs.myInputs[lastIdx].focus(); }); } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script> <div id="app"> <input type="button" @click="addEmail()" value="Add Email"/> <div v-for="(email, index) in emails" :key="index"> <input ref="myInputs" type="text" /> </div> </div>

Note that below you must put the call to focus() inside a nextTick() in order to give Vue a chance to actually render the email you just added to the list.请注意,下面您必须将调用focus()放在nextTick()中,以便让 Vue 有机会实际呈现您刚刚添加到列表中的电子邮件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM