Gnopps
Gnopps

Reputation: 349

How to use $refs in vue child component to shift focus?

I'm using this code to shift focus between text inputs in a v-for list:

HTML

<input :ref="'inputField' + index" @keydown.down="movedown(index)" type="text"
enter code here`v-model="todo.text">  

JS

movedown: function(index){
 this.$nextTick(() =>
    this.$refs["inputField" + (1 + index)][0].focus()
  );
}

It works fine when the input-fields are in the same component as the v-for. However, when I move the input-fields and the code to a child component I instead get an error that "this.$refs[("inputField" + (1 + index))] is undefined".

Here is a working JSFiddle where you can move down inputs with down-arrow: https://jsfiddle.net/Gnopps/w5xqa1r9/

Here is the same code, but in a child component and you can no longer move down: https://jsfiddle.net/Gnopps/y17en6o4/

Would anyone have any idea how I can fix this so that I can shift focus also with the input-fields in a child component?

Upvotes: 3

Views: 3108

Answers (1)

Gnopps
Gnopps

Reputation: 349

ljubadr's answer in the comments worked perferctly. Basically move ref to parent and then this.$refs["inputField" + (1 + index)][0].$el.focus():

You can try something like this. When you press down, component will emit event to parent, and parent will focus next component

Upvotes: 1

Related Questions