Sometimes, we want to fix keyup, keydown events is one character behind actual input value with Vue.js
In this article, we’ll look at how to fix keyup, keydown events is one character behind actual input value with Vue.js
How to fix keyup, keydown events one character behind with Vue.js?
To fix keyup, keydown events is one character behind actual input value with Vue.js, we can call this.$nextTick
before getting the v-model
value.
For instance, we write
<template>
<input
type="text"
v-model="keywords"
@keyup.enter="queryForKeywords"
@keydown="queryForKeywords"
/>
</template>
<script>
//...
export default {
//...
data() {
return { keywords: "" };
},
methods: {
async queryForKeywords(event) {
await this.$nextTick();
if (this.keywords.length > 2) {
console.log(this.keywords);
}
},
},
//...
};
</script>
to call the queryForKeywords
method when the keyup
or keydown
events are triggered.
In it, we call this.$nextTick
before we get the this.keywords
value to get the latest value.
this.$nextTick
delays the function until the re-rendering is done before running the code below it.
Conclusion
To fix keyup, keydown events is one character behind actual input value with Vue.js, we can call this.$nextTick
before getting the v-model
value.