Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify focus input inside v-for

I'm trying to focus on the next dynamically inserted input, I can focus foobar_x but not the ones in the v-for loop. Any help would be appreciated.

Codepen here: https://codepen.io/Moloth/pen/qPRGvz

new Vue({
  el: '#app',
  data: {
    test: "xxxxxx",
    phones: [
      {number: "0000000"},
      {number: "1111111"},    
    ],
  },
  methods: {
    focusPhones: function() {
      this.$refs.foobar_1.focus()
    },
    focusTest: function() {
      this.$refs.foobar_x.focus()
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>
<div id="app">
  <v-text-field label="foobar_x" ref="foobar_x" v-model="test"></v-text-field>
  <div v-for="(value, i) in phones" :key="i">
    <v-text-field :label="'foobar_'+i" :ref="'foobar_'+i" v-model="phones[i].number"></v-text-field>
    
  </div>
  <v-btn @click.native="focusPhones()">Focus foobar_1</v-btn>
  <v-btn @click.native="focusTest()">Focus foobar_x</v-btn>
</div>
like image 272
Soth Avatar asked Sep 26 '17 14:09

Soth


1 Answers

When you add a ref value to an element in a v-for loop an array will be generated in this.$refs['name-of-your-value'], and the reference to that element or component will be pushed to that array.

So, because you are dynamically adding a ref via :ref="'foobar_'+i", the reference to those components will be at this.$refs.foobar_0[0] and this.$refs.foobar_1[0]. But, if you just specify the same ref value (say foobar_y), Vue will do the indexing work for you and your components will be accessible at this.$refs.foobar_y[0] and this.$refs.foobar_y[1].

Here's a working example:

new Vue({
  el: '#app',
  data: {
    test: "xxxxxx",
    phones: [
      {number: "0000000"},
      {number: "1111111"},    
    ],
  },
  methods: {
    focusPhones: function() {
      this.$refs.foobar_y[1].focus()
    },
    focusTest: function() {
      this.$refs.foobar_x.focus()
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>
<div id="app">
  <v-text-field label="foobar_x" ref="foobar_x" v-model="test"></v-text-field>
  <div v-for="(value, i) in phones" :key="i">
    <v-text-field :label="'foobar_'+i" ref="foobar_y" v-model="phones[i].number"></v-text-field>
    
  </div>
  <v-btn @click.native="focusPhones()">Focus foobar_y[1]</v-btn>
  <v-btn @click.native="focusTest()">Focus foobar_x</v-btn>
</div>
like image 177
thanksd Avatar answered Oct 06 '22 00:10

thanksd