响应式原理
在上一篇文章中介绍了Vue的响应式对象,了解了Vue是如何劫持数据的,那Vue劫持数据的过程中做了什么事情呢?在数据的getter中,主要是进行依赖的收集,收集依赖这个数据的订阅者,在数据发生改变时,触发了数据的setter,主要是对订阅者进行通知,让订阅者进行更新。
这一篇文章中,我主要想介绍Vue的依赖收集和派发更新,Vue在这块逻辑中应用了发布-订阅模式,那什么是发布-订阅模式?其定义了一种依赖关系,解决了发布者与订阅者之间功能的耦合。发布-订阅模式经常被用作解决对象和类这种一对多关系的通信问题。
我们先明确一下这几个概念在Vue中分别对应什么:
- 依赖收集 -> 订阅
- 派发更新 -> 发布
- 定义的依赖关系 -> 类
Dep - 发布者 -> 响应式数据
- 订阅者 -> 渲染watcher(视图)
那我们先来看看Vue是如何进行依赖收集的把。
依赖收集
依赖收集是在getter中完成的。
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
}
// 迎合预定义的getter/setter
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
},
// ...
})
}
defineReactive一开始先创建一个Dep,然后在Dep.target存在的情况下执行dep.depend()。
Dep
Dep是依赖收集的核心,其定义在文件中:src/core/observer/dep.js
import type Watcher from './watcher'
import { remove } from '../util/index'
let uid = 0
// 一个dep是一个可观察的对象,可以有多个订阅它的指令。
class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = []
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
notify () {
// 首先稳定订阅者列表
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// 当前正在被计算的目标watcher。
// 这在全局内是唯一的,因为无论任何时候只能有一个watcher被计算。
Dep.target = null
const targetStack = []
function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
function popTarget () {
Dep.target = targetStack.pop()
}
Dep是发布-订阅模式中定义的依赖关系,其作用就是解耦响应式数据和视图的互相依赖。target是一个全局静态属性,可以理解为当前的目标watcher,也就是当前的订阅者,subs是订阅者列表,保存着所有订阅者。addSub/removeSub是新增/删除订阅者,depend将dep实例添加到当前的订阅者中(这个过程中也会将当前的订阅者添加到dep的订阅者列表中),notify是通知所有的订阅者进行更新。addSub/removeSub/notify这三个方法是发布-订阅模式中最基本的方法,使用这三个方法来对订阅者进行增/删/通知。
targetStack其实是一个栈,保存着watcher的计算顺序,因为无论任何时候只能有一个watcher被计算,当一个watcher被计算时,会先推入到targetStack中,计算结束时,会将此watcher从targetStack弹出。
那watcher是干什么事情的呢?
Watcher
Watcher其实是订阅者,Dep就是在管理Watcher,Watcher定义在文件中:src/core/observer/watcher.js
// watcher解析表达式,收集依赖项,并在表达式值更改时触发回调。 这用于$watch()和directives。
class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this
}
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
} else {
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// 为getter解析表达式
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
// 计算getter,然后重新收集依赖关系。
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// 遍历每个属性,以便将它们全部作为依赖项进行跟踪以进行深入监视
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
// 向此指令添加依赖项。
addDep (dep: Dep) {
// ...
}
// 清理依赖项集合。
cleanupDeps () {
// ...
}
// ...
}
一个Watcher,拥有很多属性和方法,其中比较核心的属性有newDeps、newDepIds、deps、depIds,比较重要的方法有get、addDep、cleanupDeps等。其构造函数主要的逻辑是处理配置,然后执行get方法。
创建watcher
我们介绍了Dep和Watcher的定义,那么这两者是怎么建立起联系的呢?我们先从创建一个watcher开始。
watcher是在mount过程中通过mountComponent创建的。核心逻辑如下:
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
// 我们在watcher的构造函数中为vm._watcher设置这个
// 因为订阅者的初始补丁可能会调用 $forceUpdate(例如,在内部子组件的mounted钩子),它依赖于已定义的 vm._watcher
new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)
实例化一个Watcher,会执行get方法,其简化逻辑是:
pushTarget(this)
value = this.getter.call(vm, vm)
popTarget()
this.cleanupDeps()
pushTarget 的逻辑是将Dep.target压入栈中,然后将Dep.target设置为当前watcher
function pushTarget (_target: Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
this.getter.call(vm, vm)其实就是执行vm._update(vm._render(), hydrating)
vm._render(),将生成VNode,这个过程中会访问vm上的数据,触发相对应的数据对象的getter,getter会执行dep.depend()【PS:这个dep是在defineReactive中创建的,每一个响应式数据持有有一个dep来管理订阅此数据的watcher(订阅者)】
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
}
depend是调用Dep.target(当前被计算的watcher)的addDep方法,并传入dep自身;addDep是将watcher订阅的响应式数据持有的dep保存起来,并调用dep.addSub(this)将当前wather保存到dep的订阅者列表subs中。这样,依赖收集基本完成,响应式数据持有的dep中保存着所有订阅此数据的watcher,而watcher中也保存着此watcher订阅到所有响应式数据持有的dep。
执行popTarget(),是将Dep.target 恢复成上一个watcher。
function popTarget () {
Dep.target = targetStack.pop()
}
最后,执行this.cleanupDeps(),进行依赖的清除。
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
deps和newDeps,前者是用来保存上一次收集的dep,后者是保存当前收集的dep。cleanupDeps的主要做的事情是,首先遍历deps,将上一次收集到的dep中这次不再收集的dep剔除掉,这样做的目的是,在新的一轮依赖收集中,将不再订阅数据的旧订阅者删除,避免无谓的通知。最后,因为已经完成依赖收集,所以需要将newDeps缓存到deps中,然后将newDeps清空。
派发更新
完成依赖收集之后,当数据发生变化的时候,就需要去通知订阅者。 派发更新的逻辑主要在setter里。
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
}
// 迎合预定义的getter/setter
const getter = property && property.get
if (!getter && arguments.length === 2) {
val = obj[key]
}
const setter = property && property.set
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
// ...
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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
setter主要有两个逻辑,一个是当shallow为false时,对其新值进行observe,使其成为一个响应式对象;另外一个是dep.notify(),对订阅者进行通知。
class Dep {
// ...
notify () {
// 首先稳定订户列表
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
notify只做一件事情,那就是把当前的订阅者进行遍历,调用其update方法。
class Watcher {
// ...
update () {
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
// ...
}
对于渲染watcher而言,update执行queueWatcher(this)。queueWatcher方法定义在文件中:src/core/observer/scheduler.js
const queue: Array<Watcher> = []
let has: { [key: number]: ?true } = {}
let waiting = false
let flushing = false
let index = 0
// 将观察者推送到观察者队列中。
// 除非刷新队列时将其推送,否则具有重复ID的任务将被跳过。
function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// 如果已经刷新,则根据其ID进行插入
// 如果已超过其ID,则将立即在下一个被运行
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
queueWatcher的逻辑并不复杂,核心就是将watcher加入到一个队列中去,这是Vue的一个优化,目的是为了不频繁地更新,而是在一个周期,对于同一个watcher只更新一次。
所以里面的逻辑会进行判断,如果队列中已经存在,则watcher不会加入队列中;如果队列没有在刷新,则直接加入队列中,反之,则根据其ID大小将其插入到队列中;最后,如果不在等待期间,则在下一个tick刷新队列flushSchedulerQueue。
flushSchedulerQueue定义在文件中:src/core/observer/scheduler.js
let flushing = false
function flushSchedulerQueue () {
flushing = true
let watcher, id
// 刷新前对队列进行排序,这样可以确保:
// 1.组件更新是从父级到子级。 (因为父级总是在子级之前创建的)
// 2.组件的user watcher在其render watcher之前运行(因为user watcher是在render watcher之前创建的)
// 3.如果某个组件在父组件的watcher运行期间被销毁,则可以跳过其watcher。
queue.sort((a, b) => a.id - b.id)
// 不缓存长度,因为在我们运行现有watcher时可能会推送更多watcher
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
id = watcher.id
has[id] = null
watcher.run()
// 在开发版本中,检查并停止循环更新。
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
// 重置状态之前保留发布队列的副本
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
resetSchedulerState()
// 调用组件updated和activated钩子
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
// devtool hook
// ...
}
flushSchedulerQueue主要的逻辑是:
- 将队列根据id大小进行排序
- 遍历队列,执行队列的每个watcher的run方法(在开发版本中,会检查是否进行死循环)
- 重置状态
- 调用组件updated和activated钩子
其中,重置状态resetSchedulerState的逻辑如下:
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0
has = {}
if (process.env.NODE_ENV !== 'production') {
circular = {}
}
waiting = flushing = false
}
主要是将各个变量的状态重置为初始状态,方便下一次刷新队列时使用。
watcher.run()的具体逻辑如下:
class Watcher {
// ...
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value ||
// 即使值相同,深度观察者和对象/数组上的观察者也应触发,因为该值可能已突变。
isObject(value) ||
this.deep
) {
// 设置新值
const oldValue = this.value
this.value = value
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`)
}
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
// ...
}
run的核心逻辑是执行this.get(),获取到最新的值,如果新值和旧值不等或者新值是对象或者是深度观察情况下,会设置新值,对于user watcher而言,会调用回调函数cb,并将新值和旧值传入。那对于render watcher呢?
其实在执行this.get()时,就会执行getter,即是:
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
所以当相应式数据发生变化时,就会触发重新渲染。
至此,当数据发生变化时,派发更新的流程基本结束。
小结
在整个依赖收集和派发更新的过程中,涉及到的主要有三方:响应式数据,Dep和Watcher,其中,Dep是发布-订阅模式的核心,它是一个桥梁,连接了响应式数据(发布者)和Watcher(订阅者),引入Dep就是为了解决两者之间的耦合,也为了解决对象(响应式数据)和类(Watcher)一对多的通信。这三者建立联系的流程如下:
- 首先,通过definReactive为数据设置getter和setter,将其转换成响应式数据,也会为数据创建一个Dep,用于管理此响应式数据的订阅者。这样,响应式数据和Dep便建立起联系,响应式数据可以告知Dep其数据发生改变;
- 接着,组件挂载过程中创建一个Watcher时,执行watcher的
get方法,会读取到依赖的响应式数据,即会触发响应式数据的getter,getter会触发响应式数据持有的dep的depend方法,这个过程会将当前Watcher保存到响应式数据持有的dep的订阅者列表(subs)中,也就完成了依赖收集。这样,订阅者和Dep便建立起联系,Dep可以对其所有订阅者发布消息。 - 当数据发生改变时,会触发数据的setter,setter会触发响应式数据持有的dep的
notify方法,通知所有的订阅者进行更新,这个过程是派发更新。
以下的图介绍了三者之间的联系:

Dep作为桥梁来沟通一个发布者和多个订阅者之间的通信。其中depend+addDep+addSub这三个属于依赖收集的流程,notify+update属于派发更新的流程。
这篇文章中主要是介绍了渲染watcher是如何工作的,如果你还想知道更多关于计算属性(computed)和监听属性(watch)这两种的watcher是如何工作的话,点击Vue的计算属性和监听属性
又或者,你想了解关于Vue的Diff算法,这篇通俗易懂的文章可以了解一下图文并茂地描绘Vue的Diff算法