数据绑定原理

前面已经讲过Vue数据绑定的原理了,现在从源码来看一下数据绑定在Vue中是如何实现的。

首先看一下Vue.js官网介绍响应式原理的这张图。

从源码角度再看数据绑定 - 图1

这张图比较清晰地展示了整个流程,首先通过一次渲染操作触发Data的getter(这里保证只有视图中需要被用到的data才会触发getter)进行依赖收集,这时候其实Watcher与data可以看成一种被绑定的状态(实际上是data的闭包中有一个Deps订阅者,在修改的时候会通知所有的Watcher观察者),在data发生变化的时候会触发它的setter,setter通知Watcher,Watcher进行回调通知组件重新渲染的函数,之后根据diff算法来决定是否发生视图的更新。

Vue在初始化组件数据时,在生命周期的beforeCreatecreated钩子函数之间实现了对data、props、computed、methods、events以及watch的处理。

initData

这里来讲一下initData,可以参考源码instance下的state.js文件,下面所有的中文注释都是我加的,英文注释是尤大加的,请不要忽略英文注释,英文注释都讲到了比较关键或者晦涩难懂的点。

加注释版的vue源码也可以直接通过传送门查看,这些是我在阅读Vue源码过程中加的注释,持续更新中。

initData主要是初始化data中的数据,将数据进行Observer,监听数据的变化,其他的监视原理一致,这里以data为例。

  1. function initData (vm: Component) {
  2. /*得到data数据*/
  3. let data = vm.$options.data
  4. data = vm._data = typeof data === 'function'
  5. ? getData(data, vm)
  6. : data || {}
  7. /*判断是否是对象*/
  8. if (!isPlainObject(data)) {
  9. data = {}
  10. process.env.NODE_ENV !== 'production' && warn(
  11. 'data functions should return an object:\n' +
  12. 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
  13. vm
  14. )
  15. }
  16. // proxy data on instance
  17. /*遍历data对象*/
  18. const keys = Object.keys(data)
  19. const props = vm.$options.props
  20. let i = keys.length
  21. //遍历data中的数据
  22. while (i--) {
  23. /*保证data中的key不与props中的key重复,props优先,如果有冲突会产生warning*/
  24. if (props && hasOwn(props, keys[i])) {
  25. process.env.NODE_ENV !== 'production' && warn(
  26. `The data property "${keys[i]}" is already declared as a prop. ` +
  27. `Use prop default value instead.`,
  28. vm
  29. )
  30. } else if (!isReserved(keys[i])) {
  31. /*判断是否是保留字段*/
  32. /*这里是我们前面讲过的代理,将data上面的属性代理到了vm实例上*/
  33. proxy(vm, `_data`, keys[i])
  34. }
  35. }
  36. /*Github:https://github.com/answershuto*/
  37. // observe data
  38. /*从这里开始我们要observe了,开始对数据进行绑定,这里有尤大大的注释asRootData,这步作为根数据,下面会进行递归observe进行对深层对象的绑定。*/
  39. observe(data, true /* asRootData */)
  40. }

其实这段代码主要做了两件事,一是将_data上面的数据代理到vm上,另一件事通过observe将所有数据变成observable。

proxy

接下来看一下proxy代理。

  1. /*添加代理*/
  2. export function proxy (target: Object, sourceKey: string, key: string) {
  3. sharedPropertyDefinition.get = function proxyGetter () {
  4. return this[sourceKey][key]
  5. }
  6. sharedPropertyDefinition.set = function proxySetter (val) {
  7. this[sourceKey][key] = val
  8. }
  9. Object.defineProperty(target, key, sharedPropertyDefinition)
  10. }

这里比较好理解,通过proxy函数将data上面的数据代理到vm上,这样就可以用app.text代替app._data.text了。

observe

接下来是observe,这个函数定义在core文件下observer的index.js文件中。

  1. /**
  2. * Attempt to create an observer instance for a value,
  3. * returns the new observer if successfully observed,
  4. * or the existing observer if the value already has one.
  5. */
  6. /*
  7. 尝试创建一个Observer实例(__ob__),如果成功创建Observer实例则返回新的Observer实例,如果已有Observer实例则返回现有的Observer实例。
  8. */
  9. export function observe (value: any, asRootData: ?boolean): Observer | void {
  10. /*判断是否是一个对象*/
  11. if (!isObject(value)) {
  12. return
  13. }
  14. let ob: Observer | void
  15. /*这里用__ob__这个属性来判断是否已经有Observer实例,如果没有Observer实例则会新建一个Observer实例并赋值给__ob__这个属性,如果已有Observer实例则直接返回该Observer实例*/
  16. if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
  17. ob = value.__ob__
  18. } else if (
  19. /*这里的判断是为了确保value是单纯的对象,而不是函数或者是Regexp等情况。*/
  20. observerState.shouldConvert &&
  21. !isServerRendering() &&
  22. (Array.isArray(value) || isPlainObject(value)) &&
  23. Object.isExtensible(value) &&
  24. !value._isVue
  25. ) {
  26. ob = new Observer(value)
  27. }
  28. if (asRootData && ob) {
  29. /*如果是根数据则计数,后面Observer中的observe的asRootData非true*/
  30. ob.vmCount++
  31. }
  32. return ob
  33. }

Vue的响应式数据都会有一个ob的属性作为标记,里面存放了该属性的观察器,也就是Observer的实例,防止重复绑定。

Observer

接下来看一下新建的Observer。Observer的作用就是遍历对象的所有属性将其进行双向绑定。

  1. /**
  2. * Observer class that are attached to each observed
  3. * object. Once attached, the observer converts target
  4. * object's property keys into getter/setters that
  5. * collect dependencies and dispatches updates.
  6. */
  7. export class {
  8. value: any;
  9. dep: Dep;
  10. vmCount: number; // number of vms that has this object as root $data
  11. constructor (value: any) {
  12. this.value = value
  13. this.dep = new Dep()
  14. this.vmCount = 0
  15. /*
  16. 将Observer实例绑定到data的__ob__属性上面去,之前说过observe的时候会先检测是否已经有__ob__对象存放Observer实例了,def方法定义可以参考https://github.com/vuejs/vue/blob/dev/src/core/util/lang.js#L16
  17. */
  18. def(value, '__ob__', this)
  19. if (Array.isArray(value)) {
  20. /*
  21. 如果是数组,将修改后可以截获响应的数组方法替换掉该数组的原型中的原生方法,达到监听数组数据变化响应的效果。
  22. 这里如果当前浏览器支持__proto__属性,则直接覆盖当前数组对象原型上的原生数组方法,如果不支持该属性,则直接覆盖数组对象的原型。
  23. */
  24. const augment = hasProto
  25. ? protoAugment /*直接覆盖原型的方法来修改目标对象*/
  26. : copyAugment /*定义(覆盖)目标对象或数组的某一个方法*/
  27. augment(value, arrayMethods, arrayKeys)
  28. /*Github:https://github.com/answershuto*/
  29. /*如果是数组则需要遍历数组的每一个成员进行observe*/
  30. this.observeArray(value)
  31. } else {
  32. /*如果是对象则直接walk进行绑定*/
  33. this.walk(value)
  34. }
  35. }
  36. /**
  37. * Walk through each property and convert them into
  38. * getter/setters. This method should only be called when
  39. * value type is Object.
  40. */
  41. walk (obj: Object) {
  42. const keys = Object.keys(obj)
  43. /*walk方法会遍历对象的每一个属性进行defineReactive绑定*/
  44. for (let i = 0; i < keys.length; i++) {
  45. defineReactive(obj, keys[i], obj[keys[i]])
  46. }
  47. }
  48. /**
  49. * Observe a list of Array items.
  50. */
  51. observeArray (items: Array<any>) {
  52. /*数组需要遍历每一个成员进行observe*/
  53. for (let i = 0, l = items.length; i < l; i++) {
  54. observe(items[i])
  55. }
  56. }
  57. }

Observer为数据加上响应式属性进行双向绑定。如果是对象则进行深度遍历,为每一个子对象都绑定上方法,如果是数组则为每一个成员都绑定上方法。

如果是修改一个数组的成员,该成员是一个对象,那只需要递归对数组的成员进行双向绑定即可。但这时候出现了一个问题:如果我们进行pop、push等操作的时候,push进去的对象根本没有进行过双向绑定,更别说pop了,那么我们如何监听数组的这些变化呢?
Vue.js提供的方法是重写push、pop、shift、unshift、splice、sort、reverse这七个数组方法。修改数组原型方法的代码可以参考observer/array.js以及observer/index.js

  1. export class Observer {
  2. value: any;
  3. dep: Dep;
  4. vmCount: number; // number of vms that has this object as root $data
  5. constructor (value: any) {
  6. //.......
  7. if (Array.isArray(value)) {
  8. /*
  9. 如果是数组,将修改后可以截获响应的数组方法替换掉该数组的原型中的原生方法,达到监听数组数据变化响应的效果。
  10. 这里如果当前浏览器支持__proto__属性,则直接覆盖当前数组对象原型上的原生数组方法,如果不支持该属性,则直接覆盖数组对象的原型。
  11. */
  12. const augment = hasProto
  13. ? protoAugment /*直接覆盖原型的方法来修改目标对象*/
  14. : copyAugment /*定义(覆盖)目标对象或数组的某一个方法*/
  15. augment(value, arrayMethods, arrayKeys)
  16. /*如果是数组则需要遍历数组的每一个成员进行observe*/
  17. this.observeArray(value)
  18. } else {
  19. /*如果是对象则直接walk进行绑定*/
  20. this.walk(value)
  21. }
  22. }
  23. }
  24. /**
  25. * Augment an target Object or Array by intercepting
  26. * the prototype chain using __proto__
  27. */
  28. /*直接覆盖原型的方法来修改目标对象或数组*/
  29. function protoAugment (target, src: Object) {
  30. /* eslint-disable no-proto */
  31. target.__proto__ = src
  32. /* eslint-enable no-proto */
  33. }
  34. /**
  35. * Augment an target Object or Array by defining
  36. * hidden properties.
  37. */
  38. /* istanbul ignore next */
  39. /*定义(覆盖)目标对象或数组的某一个方法*/
  40. function copyAugment (target: Object, src: Object, keys: Array<string>) {
  41. for (let i = 0, l = keys.length; i < l; i++) {
  42. const key = keys[i]
  43. def(target, key, src[key])
  44. }
  45. }
  1. /*
  2. * not type checking this file because flow doesn't play well with
  3. * dynamically accessing methods on Array prototype
  4. */
  5. import { def } from '../util/index'
  6. /*取得原生数组的原型*/
  7. const arrayProto = Array.prototype
  8. /*创建一个新的数组对象,修改该对象上的数组的七个方法,防止污染原生数组方法*/
  9. export const arrayMethods = Object.create(arrayProto)
  10. /**
  11. * Intercept mutating methods and emit events
  12. */
  13. /*这里重写了数组的这些方法,在保证不污染原生数组原型的情况下重写数组的这些方法,截获数组的成员发生的变化,执行原生数组操作的同时dep通知关联的所有观察者进行响应式处理*/
  14. [
  15. 'push',
  16. 'pop',
  17. 'shift',
  18. 'unshift',
  19. 'splice',
  20. 'sort',
  21. 'reverse'
  22. ]
  23. .forEach(function (method) {
  24. // cache original method
  25. /*将数组的原生方法缓存起来,后面要调用*/
  26. const original = arrayProto[method]
  27. def(arrayMethods, method, function mutator () {
  28. // avoid leaking arguments:
  29. // http://jsperf.com/closure-with-arguments
  30. let i = arguments.length
  31. const args = new Array(i)
  32. while (i--) {
  33. args[i] = arguments[i]
  34. }
  35. /*调用原生的数组方法*/
  36. const result = original.apply(this, args)
  37. /*数组新插入的元素需要重新进行observe才能响应式*/
  38. const ob = this.__ob__
  39. let inserted
  40. switch (method) {
  41. case 'push':
  42. inserted = args
  43. break
  44. case 'unshift':
  45. inserted = args
  46. break
  47. case 'splice':
  48. inserted = args.slice(2)
  49. break
  50. }
  51. if (inserted) ob.observeArray(inserted)
  52. // notify change
  53. /*dep通知所有注册的观察者进行响应式处理*/
  54. ob.dep.notify()
  55. return result
  56. })
  57. })

从数组的原型新建一个Object.create(arrayProto)对象,通过修改此原型可以保证原生数组方法不被污染。如果当前浏览器支持proto这个属性的话就可以直接覆盖该属性则使数组对象具有了重写后的数组方法。如果没有该属性的浏览器,则必须通过遍历def所有需要重写的数组方法,这种方法效率较低,所以优先使用第一种。

在保证不污染不覆盖数组原生方法添加监听,主要做了两个操作,第一是通知所有注册的观察者进行响应式处理,第二是如果是添加成员的操作,需要对新成员进行observe。

但是修改了数组的原生方法以后我们还是没法像原生数组一样直接通过数组的下标或者设置length来修改数组,可以通过Vue.set以及splice方法

Watcher

Watcher是一个观察者对象。依赖收集以后Watcher对象会被保存在Deps中,数据变动的时候会由Deps通知Watcher实例,然后由Watcher实例回调cb进行视图的更新。

  1. export default class Watcher {
  2. vm: Component;
  3. expression: string;
  4. cb: Function;
  5. id: number;
  6. deep: boolean;
  7. user: boolean;
  8. lazy: boolean;
  9. sync: boolean;
  10. dirty: boolean;
  11. active: boolean;
  12. deps: Array<Dep>;
  13. newDeps: Array<Dep>;
  14. depIds: ISet;
  15. newDepIds: ISet;
  16. getter: Function;
  17. value: any;
  18. constructor (
  19. vm: Component,
  20. expOrFn: string | Function,
  21. cb: Function,
  22. options?: Object
  23. ) {
  24. this.vm = vm
  25. /*_watchers存放订阅者实例*/
  26. vm._watchers.push(this)
  27. // options
  28. if (options) {
  29. this.deep = !!options.deep
  30. this.user = !!options.user
  31. this.lazy = !!options.lazy
  32. this.sync = !!options.sync
  33. } else {
  34. this.deep = this.user = this.lazy = this.sync = false
  35. }
  36. this.cb = cb
  37. this.id = ++uid // uid for batching
  38. this.active = true
  39. this.dirty = this.lazy // for lazy watchers
  40. this.deps = []
  41. this.newDeps = []
  42. this.depIds = new Set()
  43. this.newDepIds = new Set()
  44. this.expression = process.env.NODE_ENV !== 'production'
  45. ? expOrFn.toString()
  46. : ''
  47. // parse expression for getter
  48. /*把表达式expOrFn解析成getter*/
  49. if (typeof expOrFn === 'function') {
  50. this.getter = expOrFn
  51. } else {
  52. this.getter = parsePath(expOrFn)
  53. if (!this.getter) {
  54. this.getter = function () {}
  55. process.env.NODE_ENV !== 'production' && warn(
  56. `Failed watching path: "${expOrFn}" ` +
  57. 'Watcher only accepts simple dot-delimited paths. ' +
  58. 'For full control, use a function instead.',
  59. vm
  60. )
  61. }
  62. }
  63. this.value = this.lazy
  64. ? undefined
  65. : this.get()
  66. }
  67. /**
  68. * Evaluate the getter, and re-collect dependencies.
  69. */
  70. /*获得getter的值并且重新进行依赖收集*/
  71. get () {
  72. /*将自身watcher观察者实例设置给Dep.target,用以依赖收集。*/
  73. pushTarget(this)
  74. let value
  75. const vm = this.vm
  76. /*
  77. 执行了getter操作,看似执行了渲染操作,其实是执行了依赖收集。
  78. 在将Dep.target设置为自身观察者实例以后,执行getter操作。
  79. 譬如说现在的的data中可能有a、b、c三个数据,getter渲染需要依赖a跟c,
  80. 那么在执行getter的时候就会触发a跟c两个数据的getter函数,
  81. 在getter函数中即可判断Dep.target是否存在然后完成依赖收集,
  82. 将该观察者对象放入闭包中的Dep的subs中去。
  83. */
  84. if (this.user) {
  85. try {
  86. value = this.getter.call(vm, vm)
  87. } catch (e) {
  88. handleError(e, vm, `getter for watcher "${this.expression}"`)
  89. }
  90. } else {
  91. value = this.getter.call(vm, vm)
  92. }
  93. // "touch" every property so they are all tracked as
  94. // dependencies for deep watching
  95. /*如果存在deep,则触发每个深层对象的依赖,追踪其变化*/
  96. if (this.deep) {
  97. /*递归每一个对象或者数组,触发它们的getter,使得对象或数组的每一个成员都被依赖收集,形成一个“深(deep)”依赖关系*/
  98. traverse(value)
  99. }
  100. /*将观察者实例从target栈中取出并设置给Dep.target*/
  101. popTarget()
  102. this.cleanupDeps()
  103. return value
  104. }
  105. /**
  106. * Add a dependency to this directive.
  107. */
  108. /*添加一个依赖关系到Deps集合中*/
  109. addDep (dep: Dep) {
  110. const id = dep.id
  111. if (!this.newDepIds.has(id)) {
  112. this.newDepIds.add(id)
  113. this.newDeps.push(dep)
  114. if (!this.depIds.has(id)) {
  115. dep.addSub(this)
  116. }
  117. }
  118. }
  119. /**
  120. * Clean up for dependency collection.
  121. */
  122. /*清理依赖收集*/
  123. cleanupDeps () {
  124. /*移除所有观察者对象*/
  125. let i = this.deps.length
  126. while (i--) {
  127. const dep = this.deps[i]
  128. if (!this.newDepIds.has(dep.id)) {
  129. dep.removeSub(this)
  130. }
  131. }
  132. let tmp = this.depIds
  133. this.depIds = this.newDepIds
  134. this.newDepIds = tmp
  135. this.newDepIds.clear()
  136. tmp = this.deps
  137. this.deps = this.newDeps
  138. this.newDeps = tmp
  139. this.newDeps.length = 0
  140. }
  141. /**
  142. * Subscriber interface.
  143. * Will be called when a dependency changes.
  144. */
  145. /*
  146. 调度者接口,当依赖发生改变的时候进行回调。
  147. */
  148. update () {
  149. /* istanbul ignore else */
  150. if (this.lazy) {
  151. this.dirty = true
  152. } else if (this.sync) {
  153. /*同步则执行run直接渲染视图*/
  154. this.run()
  155. } else {
  156. /*异步推送到观察者队列中,由调度者调用。*/
  157. queueWatcher(this)
  158. }
  159. }
  160. /**
  161. * Scheduler job interface.
  162. * Will be called by the scheduler.
  163. */
  164. /*
  165. 调度者工作接口,将被调度者回调。
  166. */
  167. run () {
  168. if (this.active) {
  169. const value = this.get()
  170. if (
  171. value !== this.value ||
  172. // Deep watchers and watchers on Object/Arrays should fire even
  173. // when the value is the same, because the value may
  174. // have mutated.
  175. /*
  176. 即便值相同,拥有Deep属性的观察者以及在对象/数组上的观察者应该被触发更新,因为它们的值可能发生改变。
  177. */
  178. isObject(value) ||
  179. this.deep
  180. ) {
  181. // set new value
  182. const oldValue = this.value
  183. /*设置新的值*/
  184. this.value = value
  185. /*触发回调渲染视图*/
  186. if (this.user) {
  187. try {
  188. this.cb.call(this.vm, value, oldValue)
  189. } catch (e) {
  190. handleError(e, this.vm, `callback for watcher "${this.expression}"`)
  191. }
  192. } else {
  193. this.cb.call(this.vm, value, oldValue)
  194. }
  195. }
  196. }
  197. }
  198. /**
  199. * Evaluate the value of the watcher.
  200. * This only gets called for lazy watchers.
  201. */
  202. /*获取观察者的值*/
  203. evaluate () {
  204. this.value = this.get()
  205. this.dirty = false
  206. }
  207. /**
  208. * Depend on all deps collected by this watcher.
  209. */
  210. /*收集该watcher的所有deps依赖*/
  211. depend () {
  212. let i = this.deps.length
  213. while (i--) {
  214. this.deps[i].depend()
  215. }
  216. }
  217. /**
  218. * Remove self from all dependencies' subscriber list.
  219. */
  220. /*将自身从所有依赖收集订阅列表删除*/
  221. teardown () {
  222. if (this.active) {
  223. // remove self from vm's watcher list
  224. // this is a somewhat expensive operation so we skip it
  225. // if the vm is being destroyed.
  226. /*从vm实例的观察者列表中将自身移除,由于该操作比较耗费资源,所以如果vm实例正在被销毁则跳过该步骤。*/
  227. if (!this.vm._isBeingDestroyed) {
  228. remove(this.vm._watchers, this)
  229. }
  230. let i = this.deps.length
  231. while (i--) {
  232. this.deps[i].removeSub(this)
  233. }
  234. this.active = false
  235. }
  236. }
  237. }

Dep

来看看Dep类。其实Dep就是一个发布者,可以订阅多个观察者,依赖收集之后Deps中会存在一个或多个Watcher对象,在数据变更的时候通知所有的Watcher。

  1. /**
  2. * A dep is an observable that can have multiple
  3. * directives subscribing to it.
  4. */
  5. export default class Dep {
  6. static target: ?Watcher;
  7. id: number;
  8. subs: Array<Watcher>;
  9. constructor () {
  10. this.id = uid++
  11. this.subs = []
  12. }
  13. /*添加一个观察者对象*/
  14. addSub (sub: Watcher) {
  15. this.subs.push(sub)
  16. }
  17. /*移除一个观察者对象*/
  18. removeSub (sub: Watcher) {
  19. remove(this.subs, sub)
  20. }
  21. /*依赖收集,当存在Dep.target的时候添加观察者对象*/
  22. depend () {
  23. if (Dep.target) {
  24. Dep.target.addDep(this)
  25. }
  26. }
  27. /*通知所有订阅者*/
  28. notify () {
  29. // stabilize the subscriber list first
  30. const subs = this.subs.slice()
  31. for (let i = 0, l = subs.length; i < l; i++) {
  32. subs[i].update()
  33. }
  34. }
  35. }
  36. // the current target watcher being evaluated.
  37. // this is globally unique because there could be only one
  38. // watcher being evaluated at any time.
  39. Dep.target = null
  40. /*依赖收集完需要将Dep.target设为null,防止后面重复添加依赖。*/

defineReactive

接下来是defineReactive。defineReactive的作用是通过Object.defineProperty为数据定义上getter\setter方法,进行依赖收集后闭包中的Deps会存放Watcher对象。触发setter改变数据的时候会通知Deps订阅者通知所有的Watcher观察者对象进行试图的更新。

  1. /**
  2. * Define a reactive property on an Object.
  3. */
  4. export function defineReactive (
  5. obj: Object,
  6. key: string,
  7. val: any,
  8. customSetter?: Function
  9. ) {
  10. /*在闭包中定义一个dep对象*/
  11. const dep = new Dep()
  12. const property = Object.getOwnPropertyDescriptor(obj, key)
  13. if (property && property.configurable === false) {
  14. return
  15. }
  16. /*如果之前该对象已经预设了getter以及setter函数则将其取出来,新定义的getter/setter中会将其执行,保证不会覆盖之前已经定义的getter/setter。*/
  17. // cater for pre-defined getter/setters
  18. const getter = property && property.get
  19. const setter = property && property.set
  20. /*对象的子对象递归进行observe并返回子节点的Observer对象*/
  21. let childOb = observe(val)
  22. Object.defineProperty(obj, key, {
  23. enumerable: true,
  24. configurable: true,
  25. get: function reactiveGetter () {
  26. /*如果原本对象拥有getter方法则执行*/
  27. const value = getter ? getter.call(obj) : val
  28. if (Dep.target) {
  29. /*进行依赖收集*/
  30. dep.depend()
  31. if (childOb) {
  32. /*子对象进行依赖收集,其实就是将同一个watcher观察者实例放进了两个depend中,一个是正在本身闭包中的depend,另一个是子元素的depend*/
  33. childOb.dep.depend()
  34. }
  35. if (Array.isArray(value)) {
  36. /*是数组则需要对每一个成员都进行依赖收集,如果数组的成员还是数组,则递归。*/
  37. dependArray(value)
  38. }
  39. }
  40. return value
  41. },
  42. set: function reactiveSetter (newVal) {
  43. /*通过getter方法获取当前值,与新值进行比较,一致则不需要执行下面的操作*/
  44. const value = getter ? getter.call(obj) : val
  45. /* eslint-disable no-self-compare */
  46. if (newVal === value || (newVal !== newVal && value !== value)) {
  47. return
  48. }
  49. /* eslint-enable no-self-compare */
  50. if (process.env.NODE_ENV !== 'production' && customSetter) {
  51. customSetter()
  52. }
  53. if (setter) {
  54. /*如果原本对象拥有setter方法则执行setter*/
  55. setter.call(obj, newVal)
  56. } else {
  57. val = newVal
  58. }
  59. /*新的值需要重新进行observe,保证数据响应式*/
  60. childOb = observe(newVal)
  61. /*dep对象通知所有的观察者*/
  62. dep.notify()
  63. }
  64. })
  65. }

现在再来看这张图是不是更清晰了呢?

从源码角度再看数据绑定 - 图2