Vue.js 输入字段在输入一个字符后失去焦点 [英] Vue.js Input field loses its focus after entry of one character

查看:55
本文介绍了Vue.js 输入字段在输入一个字符后失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有输入字段的视图,它可以乘以给定的按钮.问题是在输入任何字符后,输入字段的焦点将丢失.您必须再次单击才能输入另一个字符.

有人知道可能是什么问题吗?

我的模型:

'模型':[...,'筛选': [...,'某物': ['细绳']]]

我的代码:

<input type="text" v-model.trim="model.filter.something[index]"/>

解决方案

问题是您正在使用更改值作为 key.Vue 期望 key 表示项目的唯一标识符.当您更改它时,它将成为一个新项目,必须重新渲染.

在下面的代码段中,我有两个循环,都使用相同的数据源.第一个键是您设置的方式.第二个使用 index 代替(这可能不是您需要的,但重点是使用您正在编辑的内容以外的其他内容;在此示例中,key 不是'无论如何都不需要).第一个表现出您描述的失去焦点,第二个按预期工作.

new Vue({el: '#app',数据: {'模型': {'筛选': {'某物': ['细绳']}}}});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></脚本><div id="应用程序"><div v-for="(something, index) in model.filter.something" v-bind:key="something"><input type="text" v-model.trim="model.filter.something[index]"/>{{某物}}

<div v-for="(something, index) in model.filter.something"><input type="text" v-model.trim="model.filter.something[index]" :key="index"/>{{某物}}

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>

解决方案

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>

这篇关于Vue.js 输入字段在输入一个字符后失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆