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

前端 未结 5 1351
北荒
北荒 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:56

    The component solution and deep-clone solution have their advantages, but also have issues:

    1. Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data.

    2. Deep-cloning your entire data structure every time you make a change can be very expensive.

    I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

    var vm = new Vue({
      data: {
        list: [
          {name: 'obj1 to watch'},
          {name: 'obj2 to watch'},
        ],
      },
      methods: {
        handleChange (newVal) {
          // Handle changes here!
          console.log(newVal);
        },
      },
      created () {
        this.list.forEach((val) => {
          this.$watch(() => val, this.handleChange, {deep: true});
        });
      },
    });
    

    With this structure, handleChange() will receive the specific list item that changed - from there you can do any handling you like.

    I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there).

提交回复
热议问题