3

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?

1 Answer 1

2

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
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

As I mentioned in my question, using deep watchers is computationally expensive and not recommended, especially for large data objects, which mine are. per Linus Borg, core team member: forum.vuejs.org/t/performance-cost-of-watchers-vs-emit/49626/3
Yes, deep watchers are expensive. If your objects are large - it will be better if you do not modify them directly, but use a dedicated method for each type of modification. Each of these methods will be responsible for raising the dirty flag - which can then be watched by a cheap watcher.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.