michael
michael

Reputation: 421

Vue focusing input can't find input field

I am trying to focus an input field but I get this error:

Error in nextTick: "TypeError: Cannot read property 'focus' of undefined"

Here is my code

<span
  v-show="!employeeNumberEdit"
  @click="toggleEdit(numberEdit)"
  v-html="person.number"
/>

<input
  v-show="employeeNumberEdit"
  ref="number"
>

toggleEdit: function(number){
    this.numberEdit = !number;
    if (this.numberEdit) {
      Vue.nextTick(() => {
        this.$refs.number.$el.focus();
      })
    }
}

What am I doing wrong here? Does he not know this in the callback?

Upvotes: 4

Views: 264

Answers (1)

Vipulw
Vipulw

Reputation: 1283

Your input box is this way

<input
  v-show="employeeNumberEdit"
  ref="employeeNumber"
>

And to focus in on toggle please do it this way

toggleEdit: function(number){
    this.numberEdit = !number;
    if (this.numberEdit) {
       this.$refs.employeeNumber.focus();
    }
}

Below is the running code snippet, when you press toggle button, input box will be focused.

new Vue({
     el: '#app',
     methods:{
          toggleEdit: function(number){
            this.numberEdit = !number;
            this.$refs.employeeNumber.focus();
          }
     }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input
  ref="employeeNumber"
>
<button @click="toggleEdit">Toggle</button>
</div>

Upvotes: 4

Related Questions