Reputation: 3819
I am using vue element UI.
and on user input change I want to save data (something like autosave).
So far there is one event provided by element UI, that is "change" event.
But that is also calling when I assign value from backend, in that case data are already saved.
So how to detect whether value has come from user or from our binding (I know I can take flag in this case if there is no other better solution)?
<div id="app">
<template>
<!-- `checked` should be true or false -->
<el-checkbox v-model="checked" @change="changed">Option</el-checkbox>
</template>
var Main = {
data() {
return {
checked: true
};
},methods: {
changed(val) {
alert('This should only change when user inputs, not when data is updated from code');
setTimeout(function(){
//Here alert should not appear as this is not manual input.
this.checked = !this.checked;
},5000);
}
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
Here is a codepen
https://codepen.io/hnviradiya/pen/zYORGRR
Upvotes: 0
Views: 1067
Reputation: 716
The @input
event should work well for that case. Small diference is, that it triggeres at each key down.
You could use Vue.nextTick
Before setting the value from backend in code, you could set a flag this.isSettingValue = true
. Then you set the value and call Vue.nextTick(() => { this.isSettingValue = false });
Now you can avoid autosaving by checking this.isSettingValue == true
.
Using Vue.nextTick
ensures that the flag isn't set back to false until after the asynchronous data update completes.
Vue.nextTick( [callback, context] )
Upvotes: 1
Reputation: 3819
Change event was working perfectly fine.
My mistake was (in code I had written, got answer when I wrote code for question which I took from element ui webpage when asked by @Boussadjra Brahim in comment) that I had bind it using (:) instead of (@).
So it was expecting @change
and I had provided :change
.
For more details. https://stackoverflow.com/a/46748348/9263418
Upvotes: 1