core idea
Object.defineproperty is used to add getters and setters to the data. The purpose is to automatically perform some logic when we access and write to the data: Getters do the dependency collection, setters do the update dispatch.
Vue will turn props,data, etc., into reactive objects. During creation, if the child properties are also objects, Vue will recursively turn the object into reactive objects.
The entrance
- src/core/instance/init.js
- src/core/instance/state.js
For the props
initProps
Initialization of props mainly involves traversing the props configuration defined. The process of traversal does two things: one is to call defineReactive to turn each prop value into a response, which can be accessed via vm._props. XXX to the properties that define props. The other is to proxy access to vm._props. XXX to vm.xxx via proxy.
For the data
initData
Data initialization is mainly to do two things, one is to define the data function return object traversal, through the proxy of each value vm._data.xxx to vm. XXX; The other is to call the observe method to observe the entire data change and make the data reactive.
observe
The observe method adds an Observer to the data of a non-VNode object type. If an Observer has been added, the object is returned. Otherwise, an Observer object instance is instantiated when certain conditions are met.
Observer
The constructor logic for the Observer is simple. First instantiate the Dep object, which I’ll talk about later, and then add the __ob attribute to the data object with the value of this class. The def is defined in SRC /core/util/lang.js:
defineReactive
DefineReactive initializes an instance of the Dep object, then takes obj’s property descriptor, and recursively calls observe on the child object. This ensures that all of obj’s child attributes become responsive objects, no matter how complex its structure. In this way we can access or modify one of the more deeply nested properties in OBj and also trigger the getter and setter. Finally, use object.defineProperty to add getter and setter to bj attribute key.