gpt4 book ai didi

vue.js - 防止在每个输入/惰性输入上触发输入事件?

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:14 24 4
gpt4 key购买 nike

我有一个文本字段组件,它接受一个字符串作为参数并在输入时触发一个输入事件。消费组件随后能够更新该值。

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

    <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,然后跳转到另一个输入字段,如果离开该字段,该字段将触发输入事件。我怎样才能做到这一点?

最佳答案

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

The change event is fired for input, select, and textarea elements when an alteration to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

source

另一种选择是对事件进行去抖动,如果事件在一定的延迟时间内不断重复,这将延迟事件处理程序的调用。你可以使用 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>

关于vue.js - 防止在每个输入/惰性输入上触发输入事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57266418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com