Search code examples
vuejs2dirty-checking

How to implement dirty state in VueJs


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?


Solution

  • 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
      }
    }
    });