How to track changes for array elements?

Hi,

I’d like to know if it’s still possible to track changes (new element added, or element removed) made on an array – 3 years ago, in this issue, the below code was provided:

this.$watch('list', function (value, mutation) {
    if (mutation) {
        mutation.method // e.g. 'push'
        mutation.args // raw arguments to the mutation method
        mutation.result // return value
        mutation.inserted // new, inserted elements
        mutation.removed // removed elements
    }
})

Which is exactly what I need… But it seems it doesn’t work anymore.

Any solution for this?

Thanks

I can confirm this feature doesn’t exist anymore in Vue. So I’ve had to reproduce it myself.

The below code is not bulletproof but at least it detects arr.push, arr.splice and this.$set(arr, index, something) – I also set up a quick demo:

function eventify (arr) {
  let eventify = function(arr) {
    arr.isEventified = true;
    // overwrite 'push' method
    let pushMethod = arr.push;
    arr.push = function(e) {
      pushMethod.call(arr, e);
      // the user added something into the array using 'push'
      // so at this point I can trigger my own code
    };

    // overwrite 'splice' method
    let spliceMethod = arr.splice;
    arr.splice = function() {
      let args = [], len = arguments.length;
      while (len--) args[len] = arguments[len];
      spliceMethod.apply(arr, args);
      let idx = args[0];
      let nbDel = args[1];
      let elemsLen = args.length - 2;

      if (elemsLen === 0) {
        // we reach this part of the code when the user removed some elements from the array
        nbDel += idx;
        while(idx < nbDel) {
          // element at position 'idx' has been deleted
          idx++;
        }
      }
      else if (elemsLen > 0) {
        // we reach this part of the code when the user used this.$set(list, i, "new value")
        for (let i=2; i<elemsLen+2; i++) {
          // element at position 'idx' has been changed
          idx++;
        }
      }
    };
  };

  // make sure we don't "eventify" this array
  if (!arr.isEventified) eventify(arr);
}

// watch the array called 'list'
this.eventify(list);