17

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.

Eduardo Ortiz
  • 191
  • 2
  • 6

2 Answers2

30

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();
})
kevguy
  • 4,328
  • 1
  • 24
  • 45
  • Thanks! That did the trick, I only added $el to reference the input inside the nextTick method so it ended this.$el.$refs.questionInput.focus(); and worked perfectly. – Eduardo Ortiz Aug 22 '17 at 19:04
  • Glad I could help, I'd very appreciate it if you can accept my answer. – kevguy Aug 22 '17 at 19:06
0

Try this:

var me = this;
Vue.nextTick(function() {
  me.$refs.questionInput.focus();
});
Fred K
  • 13,249
  • 14
  • 78
  • 103