admin管理员组文章数量:1279187
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.
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.
Share Improve this question asked Jan 15, 2020 at 10:18 Vijay JoshiVijay Joshi 9597 silver badges17 bronze badges 1- 1 can you please share your code? – Abu Sufian Commented Jan 15, 2020 at 10:19
2 Answers
Reset to default 8as @ramakant-mishra told you must use this.$refs
, but you need to add ref attribute dynamically on your input element also. 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./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
They key is to set ref
on all your input
s to the same string like this:
<input type="text" ref="myInputs"/>
Then you will have access to an array called this.$refs.myInputs
inside an event handler.
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./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.
本文标签: javascriptVue Set focus to dynamic input boxStack Overflow
版权声明:本文标题:javascript - Vue: Set focus to dynamic input box - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741270473a2369190.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论