Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《8分钟学会 Vue.js 原理》五、数据驱动 DOM 更新 - Watcher Observer 和 Dep #11

Open
JuniorTour opened this issue Apr 10, 2022 · 0 comments

Comments

@JuniorTour
Copy link
Owner

JuniorTour commented Apr 10, 2022

DEMO:https://jsbin.com/hehicek/edit?html,console,output

TODO 正在热火朝天更新中,欢迎催更~

Vue.js 数据驱动 && 订阅发布模式原理

Vue实例初始化时收集订阅

  1. 基于Watcher,初始化时第一次调用updateComponent()渲染出虚拟DOM:new Watcher(this, updateComponent)
  2. Watcher初始化时,constructor中会调用一次Watcher实例的回调this.get()
  3. 并将当前上下文的Dep.target设置为当前的Watcher实例
  4. 运行过程中,会读取渲染所需的data每个属性的值,触发其defineProperty()设置的getter
  5. getter中会调用dep.depend()收集当前的Dep.target作为订阅者,添加到dep实例的subs属性中
    (this.subs.push(sub))
  6. 最后,第一次调用updateComponent完成后,会卸载Dep.target,设置为null

数据驱动发布更新视图

当数据更新后,例如执行:vm._data.msg = "数据驱动 DOM 更新”

  1. 会触发赋值属性对应的defineProperty()设置的setter
  2. setter中会调用dep.notify(),遍历所有的订阅者(this.subs),并调用订阅者的.update()方法发布更新
  3. Watcher.update()方法会再次调用其第二个参数回调函数,执行一次updateComponent
  4. 执行updateComponent,调用_render(),渲染出新的虚拟DOM,经过Diff,同步到真实DOM中,就完成了一轮「数据驱动」的视图更新。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant