Vue 中组件实例对应的 watcher, data 变动是如何通知它的,data 如何知道 watcher 的存在?

如果说 watcher 修改了 data 中的属性访问和设置,并将属性添加为依赖,那么毫无疑问,watcher 是知道 data 的,可是作为依赖的 data 是如何知道 watcher 的存在的呢?

回复
阅读 1.7k
2 个回答
observer/index.js

export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()

const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {

return

}

// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {

val = obj[key]

}

let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {

enumerable: true,
configurable: true,
get: function reactiveGetter () {
  const value = getter ? getter.call(obj) : val
  if (Dep.target) {
    dep.depend()
    if (childOb) {
      childOb.dep.depend()
      if (Array.isArray(value)) {
        dependArray(value)
      }
    }
  }
  return value
},
set: function reactiveSetter (newVal) {
  const value = getter ? getter.call(obj) : val
  /* eslint-disable no-self-compare */
  if (newVal === value || (newVal !== newVal && value !== value)) {
    return
  }
  /* eslint-enable no-self-compare */
  if (process.env.NODE_ENV !== 'production' && customSetter) {
    customSetter()
  }
  // #7981: for accessor properties without setter
  if (getter && !setter) return
  if (setter) {
    setter.call(obj, newVal)
  } else {
    val = newVal
  }
  childOb = !shallow && observe(newVal)
  dep.notify()
}

})
}

observer data,然后通过render函数(下面的代码就是生成的render函数)触发get,收集对应watcher

   with(this){return _c('div',{attrs:{"id":"app"}},[_c('p',{attrs:{"id":"msg"}},[_v(_s(msg))]),_v(" "),_c('p',{class:{p1: usep1}},[_v(_s(msg))]),_v(" "),(show)?_c('p',[_v(_s(msg))]):_e(),…

然后对应data改变时,触发set,执行dep.notify(),取出watcher更新dom.
详细自己断点调试。

vuejs响应式原理真的是超级难以理解,data 中的每个 key 都会对应一个 dep,dep 里面管理的是 targetFunction 列表,实际上是 renderFunction。当 key set 的时候,调用 dep.notify() 实际上干的事情是执行 target。target 能获得 data[key] 并且 render,那 watcher 呢,设置 target 吗?彻底懵了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏