【问题标题】:prevent input event firing on each input / lazy input?防止在每个输入/惰性输入上触发输入事件?
【发布时间】:2019-07-30 17:28:50
【问题描述】:

我有一个文本字段组件,它将字符串作为参数并在输入时触发输入事件。然后消费组件就可以更新这个值了。

此输入组件使用此示例代码

    <template>
      <v-text-field label="Your input here" :value="name" @input="input"></v-text-field>
    </template>

    <script>
    export default {
      props: {
        name: {
          type: String,
          required: true
        }
      },
      methods: {
        input: function(v) {
          this.$emit("input", v);
        }
      }
    };
    </script>

消费组件可以使用这个示例代码

    <template>
      <v-app>
        <v-card>
          <v-card-title>Your name is: {{name}}</v-card-title>
          <NameInput :name="name" @input="fieldUpdated"/>
        </v-card>
      </v-app>
    </template>

    <script>
    import NameInput from "./components/NameInput";

    export default {
      components: {
        NameInput
      },
      data: function() {
        return {
          name: "The initial name"
        };
      },
      methods: {
        fieldUpdated: function(name) {
          this.name = name;
        }
      }
    };
    </script>

这种方法非常有效,但我们假设 NameInput 组件将处理 ID,而 fieldUpdated 方法将根据提供的 ID 输入触发 API 调用。 ID 的长度为 8 个字符,输入此 ID 时,API 调用将失败 7 次,然后才写入正确的 ID。

我想提供一个选项来防止在每个输入上触发输入事件。

假设我将输入 ID,然后跳转到另一个输入字段,离开该字段,该字段将触发输入事件。我怎样才能做到这一点?

【问题讨论】:

  • 听起来像@blur
  • 我现在在文档中找到了@blur,但这只会给我一个布尔值。那么如何传回当前的文本字段值呢?
  • 您可以使用@change。另一种选择是研究去抖动。
  • 在调用 API 之前检查长度如何?
  • @Husam Ibrahim 如果你愿意,你可以回答这个问题

标签: vue.js vuetify.js


【解决方案1】:

一种选择是使用change 事件而不是input,它只会在文本字段中的值发生变化并且失去焦点时触发..

change 事件为 input、select 和 textarea 触发 元素值的更改由 用户。与input 事件不同,change 事件不一定 每次更改元素的值都会触发。

source

另一个选项是debounce事件,如果事件在一定的延迟时间内不断重复,这将延迟事件处理程序的调用。你可以使用 lodash 的 debounce 方法。例如..

<template>
  <v-text-field label="Your input here" :value="name" @input="debouncedInput"></v-text-field>
</template>

<script>
  import debounce from 'lodash.debounce'

  export default {
    props: {
      name: {
        type: String,
        required: true
      }
    },
    methods: {
      // debounce input 300ms
      debouncedInput: debounce(function(v) {
        this.$emit("input", v);
      }, 300)
    }
  };
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多