I am new to VueJs and I am working on a form that I want to enable the Save
button only when a change occurs at the model.
My initial thought is to compute
a dirty function comparing the initial model with the current.
Note: This code is not tested, it's here just for an example.
var app = new Vue({
el: '#app',
data: {a:0, b:'', c:{c1:null, c2:0, c3:'test'}},
initialData: null,
mounted():{ initialData = JSON.parse(JSON.stringify(data));},
computed: {
isDirty: function () {
return JSON.stringify(data) === JSON.stringify(initialData)
}
}
});
Is there a better way of doing this or is there any improvement you could suggest on the above-mentioned code?
You can use the deep
option of watch
as shown in the manual
var app = new Vue({
el: '#app',
data:
{
model:
{
a:0,
b:'',
c:
{
c1:null,
c2:0,
c3:'test'
}
},
dirty: false
},
watch:
{
model:
{
handler(newVal, oldVal)
{
this.dirty = true;
},
deep: true
}
}
});
Borrowing from -- > https://stackoverflow.com/a/48579303/4050261
You can bind single onchange
event on the parent container and benefit from the fact that change events bubble:
<div class="container" @change="someThingChanged()">
<input v-model="foo">
<input v-model="bar">
... etc.
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With