yourivdloo
yourivdloo

Reputation: 423

Vue put focus on an input via refs

I use v-for to create inputs foreach item in a list, i assign a ref in the following way

:ref="`input-${index}`"

which makes my $refs look like this

enter image description here

Now my question is; on the addition of an input I also want to put focus on the last input, however I can't manage to make it work.

Right now I tried something like this,

this.$refs["input-" + index.toString()].focus()

however I feel like it has to do with the structure of refs I don't know how to deal with.

Does anybody know how I can access each input and how to focus it (i guess just .focus()).

Upvotes: 1

Views: 1501

Answers (2)

yourivdloo
yourivdloo

Reputation: 423

So I do not know exactly anymore, however I remember that the problem was that I was putting focus on the ion-item rather than the ion-input. I needed to add .children[i] (i depending on what child it is). this allowed me to put focus in the input :)

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

It seems that you're using ref inside a v-for loop, in this case is recommended to use the ref in the root element containing the v-for directive as follows :

 <input v-for="(item, index) in items" ref="inputs" .../>

this will create an array of the referenced elements that you could use them like :

 this.$refs.inputs[someIndex].focus()

or

 this.$refs.inputs[this.$refs.inputs.length-1].focus() // focus on the last input

Upvotes: 1

Related Questions