The introduction

We know that in Vue we listen for an Object in vue2.x using Object.defineProperty(), but this method has some disadvantages.

  • One is that only one property of an object can be data-jacked, and if the object also contains objects, the API needs to be used recursively
  • The other is that you can’t listen on arrays. You can only listen on arrays by adding an interceptor using Object.defineProperty between Arrar. Prototype and the array instance
new Vue({
    el : '#app'.data : {
        nums: []},methods : {
        add() {
            this.nums.push(1)}}})Copy the code

What if, in the example above, the push method is used to change the array and does not trigger the getter/setter?

To track changes

Well, let’s write it down briefly

const nums = [1.2.3];

const ArrayProto = Array.prototype;

const arrayArguments = [];

const ArrayMethods = ['push'];

ArrayMethods.forEach((method) = > {
    // The native method
    let orginal = ArrayProto[method];

    arrayArguments[method] = function() {
        console.log('push');

        return orginal.apply(this.arguments); }})/ / the key
nums.__proto__ = arrayArguments;

nums.push(1);


console.log(nums)
Copy the code