Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lagging in v-on:change

Tags:

vue.js

I had an input with v-on:change directive in it to call some method I declared inside the Vue objects. But I realized there are delays in calling the method whenever the value is changed.

I reproduced it in here:

HTML

<div id="demo">    
    <input type="number" min=0 v-on:change="change">
    <p>{{num}}</p>
</div>

Javascript

var data = {
    num:0
}

var demo = new Vue({
    el: '#demo',
    data: data,
  methods: {
    change: function(event) {
        console.log(event.target.value);
      this.num = event.target.value;
    }
  }
})

https://jsfiddle.net/lookman/4y2wmxot/2/

like image 849
geckob Avatar asked Dec 08 '22 20:12

geckob


2 Answers

There is no delay actually, unless you click outside the input field in result section, on-change will not be triggered. It is triggered when focus changes from the input field, as you have only one element this is triggered when you click manually in the result section.

If you just add one more component, like I did here, and now you enter some value and press tab, you will see change immediately, you can do this in your fiddle also, enter value and press tab (which will remove focus)

If you want to trigger on each change

You can use input event instead of change event to trigger the method for each change.

The DOM input event is fired synchronously when the value of an or element is changed.

Code changes:

<input type="number" min=0 v-on:input="change">

Update fiddle: https://jsfiddle.net/4y2wmxot/4/

like image 155
Saurabh Avatar answered Dec 11 '22 07:12

Saurabh


For this use case, you really should be using v-model anyways:

<div id="demo">    
    <input type="number" min=0 v-model="num">
    <p>{{num}}</p>
</div>

Then there's no need for the method at all:

var data = {
    num:0
}

var demo = new Vue({
    el: '#demo',
    data: data,
})
like image 41
ceejayoz Avatar answered Dec 11 '22 08:12

ceejayoz