Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on input after it's showed by v-show

I have a simple form that is hidden when the page is loaded, using v-show. I want to focus the input after showing it. I have a button to call a a method that shows the form and sets the focus to the input using this code:

    this.newQuestion = true; //(Form whit v-show:newQuestion)
    this.$refs.questionInput.focus();

The problem is that the form is showed correctly, but the input isn't focused the first time I press the button, if I press it for a second time when the form is in the page it works. I want to know if there is a way to do this, thanks.

like image 776
Eduardo Ortiz Avatar asked Aug 22 '17 18:08

Eduardo Ortiz


People also ask

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How do you set focus on Vue?

Here, we wrap our call to focusInput inside of a nextTick . Using nextTick will allow us to wait until the input is rendered in the DOM. Once it's there, then we can grab it, and focus on it. You can read more about using nextTick on the docs.


1 Answers

I encountered a similar problem before, and I forced the update (in your case, the focus) by using Vue's nextTick method, which is to use immediately after you’ve changed some data to wait for the DOM update.:

this.$nextTick(() => {
    this.$refs.questionInput.focus();
})
like image 135
kevguy Avatar answered Oct 16 '22 12:10

kevguy