Vue Set Focus On Input

Posted on  by admin
Sometimes it’s important to set focus on input (programmatically or by default), it is often for accessibility, and/or to make the app more convenient to use purposes.

the usual is setting it to be autofocused at Page load:. The only problem is that when you add the autofocus attribute to an input it will be focused once is loaded, but when you init a Vue app the focus is lost so you need to programmatically focus an element.

To use focus() programmatically you use either Vuejs or vanilla javascript:.

→ in Javascript:. Now grap you element using getElementById(). Now all you have to do is to call the focus() function:. → in Vue.js:Vue offers a better and easy way:. note: Vue uses ref="something" attribute to register a reference to any HTML element or child component.

Then you use $refs, which are a much more reliable way of grabbing your elements.

Now you are allowed to use that within your method:.

Cyril N.Cyril N.
37.3k1

For instance, if you change the inputs’ status from being hidden to being displayed.You’ll need to wait for the input to be rendered before you can grab it and focus on it.

To do this you can use a method to check if the element you want to focus Is visible or not.Here is an example:.

Grzegorz Luczywo
9,254