Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 791
Menelaos Vergis Avatar asked Sep 15 '18 08:09

Menelaos Vergis


2 Answers

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
  }
}
});
like image 200
IVO GELOV Avatar answered Sep 20 '22 05:09

IVO GELOV


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>
like image 43
Adarsh Madrecha Avatar answered Sep 19 '22 05:09

Adarsh Madrecha