我有一个textfield组件,它将字符串作为参数并在输入上触发输入事件。然后,使用方组件可以更新此值。
此输入组件使用此示例代码
<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>
Run Code Online (Sandbox Code Playgroud)
消费组件可以使用此示例代码
<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>
Run Code Online (Sandbox Code Playgroud)
这种方法确实很好用,但让我们假设NameInput组件将处理ID,并且该fieldUpdated方法将根据提供的ID输入触发API调用。该ID的长度为8个字符,并且在键入此ID时,API调用将失败7次,然后再写入正确的ID。
我想提供一个选项,以防止在每个输入上触发输入事件。
假设我要输入ID,然后跳到另一个输入字段,然后离开该字段将触发输入事件。我该如何实现?
一种选择是使用change事件而不是事件input,只有当文本字段中的值发生变化并且失去焦点时才会触发事件。
当用户提交对元素值的更改时,将针对、和元素触发该
change事件。与事件不同的是,元素值的每次更改不一定都会触发事件。inputselecttextareainputchange
另一种选择是对事件进行反跳,如果事件在一定的延迟时间内不断重复,这将延迟事件处理程序的调用。您可以使用 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |