SoFunction
Updated on 2025-04-05

Vue source code learning object attribute monitoring

This article introduces the object attribute monitoring of vue source code learning, and shares it with you, as follows:

Reference versionvue source code version: 0.11

Related

The key to implementing two-way data binding for vue is, let's take a look at this function first.

View related on MDN explanation.

Let's start with the simplest:

let a = {'b': 1};
(a, 'b', {
  enumerable: false,
  configurable: false,
  get: function(){
    ('b' + 'Accessed');
  },
  set: function(newVal){
    ('b' + 'Modified, new' + 'b' + '=' + newVal);
  }
});

 = 2;  // b is modified, new b=2;    // b is accessed

In this way, we can monitor the object! But the problem is not that simple. . .

We may have nested situations such as the values ​​of attributes in objects or objects, which can be solved through recursion!

In vue source code file

// Observer constructorfunction Observer(data){
   = data;
  (data);
}

let p = ;
 = function(obj){
  let val;
  for(let key in obj){
    // Filter out the properties owned by an object through hasOwnProperty    if((key)){
      val = obj[key];
      // Recursive call loops out all objects      if(typeof val === 'object'){
        new Observer(val);
      }
      (key, val);
    }
  }
};

 = function(key, val){
  (, key, {
    enumerable: false,
    configurable: false,
    get: function(){
      (key + 'Accessed');
    },
    set: function(newVal){
      (key + 'Modified, new' + key + '=' + newVal);
      if(newVal === val) return ;
      val = newVal;
    }
  })
};

let data = {
  user: {
    name: 'zhangsan',
    age: 14
  },
  address: {
    city: 'beijing'
  }
}

let app = new Observer(data);
;  // user is accessed

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.