Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js keyup, keydown events one character behind

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);
    }
like image 958
farbodg Avatar asked Feb 21 '18 19:02

farbodg


1 Answers

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>
like image 130
thanksd Avatar answered Oct 26 '22 03:10

thanksd