Vue - Deep watching an array of objects and calculating the change?

前端 未结 5 1304
北荒
北荒 2020-11-28 03:10

I have an array called people that contains objects as follows:

Before

[
  {id: 0, name: \'Bob\', age: 27},
  {id: 1, n         


        
5条回答
  •  遥遥无期
    2020-11-28 03:35

    I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

    Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

    new Vue({
      methods: {
        setValue: function() {
          this.$data.oldPeople = _.cloneDeep(this.$data.people);
        },
      },
      mounted() {
        this.setValue();
      },
      el: '#app',
      data: {
        people: [
          {id: 0, name: 'Bob', age: 27},
          {id: 1, name: 'Frank', age: 32},
          {id: 2, name: 'Joe', age: 38}
        ],
        oldPeople: []
      },
      watch: {
        people: {
          handler: function (after, before) {
            // Return the object that changed
            var vm = this;
            let changed = after.filter( function( p, idx ) {
              return Object.keys(p).some( function( prop ) {
                return p[prop] !== vm.$data.oldPeople[idx][prop];
              })
            })
            // Log it
            vm.setValue();
            console.log(changed)
          },
          deep: true,
        }
      }
    })
    

    See the updated codepen

提交回复
热议问题