Reputation: 1555
In a Vue JS project, i have the following pretty standard pattern:
data () {
model: {
id: uid(),
label: null,
options: []
.... etc.
}
}
The model
property feeds a form and I need to show an alert when the data model is 'dirty' - any key may have been changed by the user since last saving.
The problem is - the data may be affected many different methods - v-model for inputs, custom events from child components like selects and toggle switches etc and the options array maybe edited by drag-and-drop sorting, adding/removing elements, etc.
I'm looking for - ideally - a single REACTIVE (eg computed) property I can watch to know if the model is dirty so I can prompt the user to save.
Does Vue have a hidden or undocumented property/method, something like $vm._isDirty? I know I can use a compare fn to handle it manually, but it's not reactive, and I know I could use a deep watcher on the model, but that's computationally expensive and some of these models are pretty big.
What approach have other developers have used?
Upvotes: 1
Views: 1237
Reputation: 14259
You can simply use a deep watcher:
watch:
{
model:
{
deep: true,
handler(newValue, oldValue)
{
this.modified = true; // or whatever you need to do when the model becomes dirty
}
}
}
Upvotes: 1