dhee
dhee

Reputation: 109

Vuejs watch dynamic array element on change

I'm creating this text editor, with the field of name, and address

<ckeditor :editor="editor" v-model="data[index].name">
<ckeditor :editor="editor" v-model="data[index].address.1">
<ckeditor :editor="editor" v-model="data[index].address.2">

and the data property

 data() {
    return {
        data:[],
        index:0,
        editor: customedit
    };
  },

the editor also have two button, next and back, with the method add and substracting "index". the data, is loaded before mount from server, with structure like this

serverdata = [{name:'name1',address:{1:'address 1',2:'address 2'}} , {name:'name2',address:{1:'address 4',2:'address 4'}}]

so what I want to do is, after data from server is loaded, user can move between data, and when user make change to it, the data index that user make change to will be logged. so far I have been using deep watcher like this:

watch: {
    data: {
      handler(val) {
          console.log('the data is changed');
          console.log(this.index + 1);
      },
      deep: true
    }
  },

but even when there are no change, when I click next, the log is shown, thanks for any help/suggestion

Upvotes: 0

Views: 1244

Answers (1)

alpachino
alpachino

Reputation: 79

Maybe you may compare new and old value if they are different do the console.log. You can receive two parameters in the function something like this:

handler(newValue, oldValue) {
         if(newValue !== oldValue) {
          console.log('the data is changed');
          console.log(this.index + 1);
         }
      },
     deep: true

You can compare the content in the array with:

if(JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
          console.log('the data is changed');
          console.log(this.index + 1);
         }
      },
     deep: true

Okay your problems seems you are receiving the same values in old and new values. You can try to watch a computed property and use that to convert array into string.Even with that string you can reconstruct the old array. I try to do a example:

data() {
    return {
        yourArray: []
    }
},
computed: {
    yourArrayStr: function () { 
        return JSON.stringify(this.yourArray)
    }
},
watch: {
    yourArrayStr: function(newValue, oldValue) {
        if(newValue !== oldValue){
            let oldValueArray = JSON.parse(oldValue);
            console.log();
            console.log();
        }
    },
}

Upvotes: 1

Related Questions