Sometimes, we want to put focus on an input with Vue.js and JavaScript.
In this article, we’ll look at how to put focus on an input with Vue.js and JavaScript.
How to put focus on an input with Vue.js and JavaScript?
To put focus on an input with Vue.js and JavaScript, we can assign a ref to the input.
And then we can get the input with the ref and call focus
to focus the input.
For instance, we write:
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id='app'>
</div>
to add the Vue script and an app container.
Then we write:
const v = new Vue({
el: '#app',
template: `
<div>
<input ref='input'>
</div>
`,
mounted() {
this.$refs.input.focus()
}
})
We add an input in the template and assign a ref to it by setting the ref
prop to input
.
Then in the mounted
hook, we get the input with this.$refs.input
.
And then we call focus
on it the put focus on the input.
Conclusion
To put focus on an input with Vue.js and JavaScript, we can assign a ref to the input.
And then we can get the input with the ref and call focus
to focus the input.