返回

Vue 源码分析之 Watcher(一)

前端

Vue 的响应式系统

Vue 是一个优秀的 MVVM 框架,其核心之一就是响应式系统。响应式系统使得 Vue 能够自动追踪和响应数据的变化,并自动更新视图。

Watcher 是 Vue 响应式系统中的一个重要概念。Watcher 是一个对象,它负责监听数据的变化,当数据变化时,它会通知 Vue 实例更新视图。

Watcher 构造函数

Watcher 构造函数的定义如下:

function Watcher (
  vm: Component,
  expOrFn: string | Function,
  cb: Function,
  options?: WatcherOptions,
  isRenderWatcher?: boolean
) {
  this.vm = vm
  vm._watchers.push(this)
  this.expression = expOrFn
  this.cb = cb
  this.active = true
  this.lazy = !!options.lazy
  this.dirty = this.lazy
  this.deps = []
  this.newDeps = []
  this.depIds = new Set()
  this.newDepIds = new Set()
  this.before = options.before
  this.getter = options.getter && !options.lazy
    ? options.getter
    : this.parseGetter(expOrFn)
  this.value = this.lazy
    ? undefined
    : this.get()
}

Watcher 构造函数参数

Watcher 构造函数的参数如下:

  • vm: Vue 实例。
  • expOrFn: 要监听的表达式或函数。
  • cb: 当表达式或函数的值发生变化时,要执行的回调函数。
  • options: Watcher 的选项。
  • isRenderWatcher: 是否是渲染 Watcher。

Watcher 的属性和方法

Watcher 的属性和方法如下:

  • vm: Vue 实例。
  • expression: 要监听的表达式或函数。
  • cb: 当表达式或函数的值发生变化时,要执行的回调函数。
  • active: Watcher 是否处于激活状态。
  • lazy: Watcher 是否是惰性 Watcher。
  • dirty: Watcher 是否需要更新。
  • deps: Watcher 依赖的 Dep 数组。
  • newDeps: Watcher 新依赖的 Dep 数组。
  • depIds: Watcher 依赖的 Dep 的 ID 集合。
  • newDepIds: Watcher 新依赖的 Dep 的 ID 集合。
  • before: Watcher 在更新视图之前要执行的函数。
  • getter: Watcher 用于获取数据的函数。
  • value: Watcher 当前的值。

Watcher 的工作流程

Watcher 的工作流程如下:

  1. Watcher 被创建。
  2. Watcher 开始监听数据。
  3. 当数据发生变化时,Watcher 会被通知。
  4. Watcher 执行回调函数。
  5. Watcher 更新视图。

总结

Watcher 是 Vue 响应式系统中的一个重要概念。通过查看 Vue 源码来具体分析 Watcher 构造函数的实现细节,查看 Watcher 各个参数的具体含义,深入理解了 Vue 的响应式系统是如何工作的。