Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  40] [ 5]  / answers: 1 / hits: 24582  / 6 Years ago, wed, february 21, 2018, 12:00:00

I'm using the keydown/keyup events which call a javascript function that prints the value of input box to the console (and also the value of the currentTarget field of the event), and I am noticing it is a character late. For example, if I type hello into the input box, I only see hell in the console, until I press another key and then I see hello, even though by this point I've typed hello1. Why is this? And is there anyway around it?



Here's the HTML:



<input type=text class=form__field v-model=keywords v-on:keyup.enter=queryForKeywords v-on:keydown=queryForKeywords>


And the JS:



queryForKeywords: function(event) {
var self = this;
if (this.keywords.length > 2) {
console.log(keywords value: + this.keywords);
console.log(event value: + event.currentTarget.value);
}

More From » vue.js

 Answers
3

Because you are depending on the input's v-model to update the keywords property, the value won't update until the Vue component has re-rendered.


You can access the updated value of keywords in a callback passed to this.$nextTick like in this example:




new Vue({
el: '#app',
data() {
return { keywords: '' }
},
methods: {
queryForKeywords: function(event) {
this.$nextTick(() => {
if (this.keywords.length > 2) {
console.log(keywords value: + this.keywords);
}
});
}
}
})

<script src=https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js></script>
<div id=app>
<input type=text class=form__field v-model=keywords v-on:keyup.enter=queryForKeywords v-on:keydown=queryForKeywords>
</div>




[#55093] Saturday, February 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sienad

Total Points: 208
Total Questions: 100
Total Answers: 77

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;