Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js Input field loses its focus after entry of one character

I have a view with an input field, which can be multiplicated by a given button. The problem is that after any entry of a char, the focus of the input field is lost. You have to click again to enter another char.

Do someone have a clue what could be the problem?

My model:

'model': [
    ...,
    'filter': [
        ...,
        'something': [
            'string'
        ]
    ]
]

My code:

<div v-for="(something, index) in model.filter.something" v-bind:key="something">
    <input type="text" v-model.trim="model.filter.something[index]"/>
</div>
like image 419
crazyyou Avatar asked Mar 28 '17 15:03

crazyyou


1 Answers

The problem is that you are using a changing value as key. Vue expects key to indicate a unique identifier for the item. When you change it, it becomes a new item and must be re-rendered.

In the snippet below, I have two loops, both using the same data source. The first is keyed the way you have it set up. The second uses index instead (that may not be what you need, but the point is to use something other than what you're editing; in this example, key isn't needed anyway). The first exhibits the loss-of-focus you describe, the second works as expected.

new Vue({
  el: '#app',
  data: {
    'model': {
      'filter': {
        'something': [
          'string'
        ]
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <div v-for="(something, index) in model.filter.something" v-bind:key="something">
    <input type="text" v-model.trim="model.filter.something[index]" />
    {{something}}
  </div>
  <div v-for="(something, index) in model.filter.something">
    <input type="text" v-model.trim="model.filter.something[index]" :key="index" />
    {{something}}
  </div>
</div>
like image 66
Roy J Avatar answered Oct 18 '22 09:10

Roy J