文章目录
Vue2 源码解读一:Global API
Vue2 源码解读二:mergeOptions
Vue2 源码解读三:Vue实例
Vue2 源码解读四:Observer模块
1、整体过程
2、Observer
3、Dep
4、Watcher
5、Array劫持
6、traverse
7、scheduler
Vue2 源码解读四:Observer模块
深入理解Vue的响应式原理,需要先熟悉JavaScript的一些基础知识,比如 继承与原型链、
Object.defineProperty
(Vue做数据劫持最核心的方法)、Object.create
等等,然后才能理解Vue源码中的一些写法。
官方说明:Vue2 - 深入响应式原理
1、整体过程
- 在initState时,
initProps()
给props添加响应式;initComputed()
给每一个computed属性创建一个Watcher;initWatch()
给每一个watch属性创建一个Watcher;initData()
给data创建一个根节点的观察者Observer,然后给data添加响应式,并创建对应的Dep对象,然后在创建Watcher时,会触发响应式属性的geter方法,在此时,该watcher会通过depend方法加入响应式属性Dep对象的subs订阅者列表中。 - 执行mount挂载操作时,每个组件实例都对应一个渲染watcher对象。
- 当数据发生变化时,会先触发数据的setter方法,然后触发dep的notify方法,该方法遍历subs订阅者列表,并执行每一个sub的update方法,然后执行sub(Watcher对象)的getter,以及cb回调函数。如果为reader watcher(渲染监听器),getter为updateComponent函数,此函数调用vm._update()刷新页面状态。
大致的流程图如下:
2、Observer
Observer作为观察者,主要对外的方法有:
Observer构造方法
:给监听的数据(对象、数组)递归添加_ob_属性。observe()
:为value创建一个观察者Observer,已有观察者的,则返回现有的观察者。defineReactive()
:通过Object.defineProperty
劫持getter、setter,并创建对应的dep对象。
Observer模块的入口文件src/core/observer/index.js
:
/* @flow */
import Dep from './dep'
import VNode from '../vdom/vnode'
import { arrayMethods } from './array'
import {
def,
warn,
hasOwn,
hasProto,
isObject,
isPlainObject,
isPrimitive,
isUndef,
isValidArrayIndex,
isServerRendering
} from '../util/index'
const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
/**
* In some cases we may want to disable observation inside a component's
* update computation.
*/
export let shouldObserve: boolean = true
// 用于控制是否创建观察者
export function toggleObserving (value: boolean) {
shouldObserve = value
}
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*
* 观察者类
*/
export class Observer {
value: any; // 观察对象
dep: Dep; // 依赖项
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
// 给value添加__ob__可写的数据描述符,值为当前观察者类
def(value, '__ob__', this)
// 添加监听
if (Array.isArray(value)) {
// 如果是数组
if (hasProto) {
// 如果支持_proto_,则替换value数组的_proto_,拦截数组一些原生的方法(pop、push、splice等等)
protoAugment(value, arrayMethods)
} else {
// 如果不支持_proto_,则通过定义隐藏属性来扩充value数组
copyAugment(value, arrayMethods, arrayKeys)
}
// 监听数组中的每一项
this.observeArray(value)
} else {
// 遍历所有属性并将它们转换为getter/setter
this.walk(value)
}
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*
* 遍历所有属性并将它们转换为getter/setter
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
/**
* Observe a list of Array items.
* 监听数组中的每一项
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
// helpers
/**
* Augment a target Object or Array by intercepting
* the prototype chain using __proto__
* 使用_proto_来拦截原型链来扩展target对象或者数组
*/
function protoAugment (target, src: Object) {
/* eslint-disable no-proto */
target.__proto__ = src
/* eslint-enable no-proto */
}
/**
* Augment a target Object or Array by defining
* hidden properties.
* 通过定义隐藏属性来扩充目标对象或数组
*/
/* istanbul ignore next */
function copyAugment (target: Object, src: Object, keys: Array<string>) {
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i]
// 给tartget扩展key隐藏属性,值为src[key]
def(target, key, src[key])
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*
* 为value创建一个观察者Observer,已有的观察者,则返回现有的观察者。
*/
export function observe (value: any, asRootData: ?boolean): Observer | void {
// 非Object,或者VNode直接返回
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
// 如果已有观察者
ob = value.__ob__
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
// 已打开观察、非服务器端渲染、是数组或者对象、可扩展对象、非Vue实例
// 则为value创建观察者Observer
ob = new Observer(value)
}
// 如果是根节点的数据,则vmCount++
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
/**
* Define a reactive property on an Object.
* 为对象添加响应式属性
* 会创建Dep,如果obj的key属性没有观察者,则创建观察者
*/
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) {
// 属性描述符没有getter或者拥有setter、参数只有obj和key
// 则赋值value
val = obj[key]
}
// 非浅观察,则为val创建观察者
// 在这里做的递归,会给val下的所有Object、Array都添加上监听器
let childOb = !shallow && observe(val)
// 给obj对象的key属性添加get/set劫持
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()
}
})
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
export function set (target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
// 有效数组,调用splice添加
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
// 这里的splice已经被Vue拦截,会触发dep.update
target.splice(key, 1, val)
return val
}
// 如果target属性已存在,直接设置即可
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
// 如果target不存在监听器,直接设置属性
if (!ob) {
target[key] = val
return val
}
// 添加响应式属性
defineReactive(ob.value, key, val)
// 通知更新
ob.dep.notify()
return val
}
/**
* Delete a property and trigger change if necessary.
*/
export function del (target: Array<any> | Object, key: any) {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
// 有效数组,调用splice删除
if (Array.isArray(target) && isValidArrayIndex(key)) {
// 这里的splice已经被Vue拦截,会触发dep.update
target.splice(key, 1)
return
}
// 获取Vue监听器
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
)
return
}
if (!hasOwn(target, key)) {
return
}
// 对象:通过delete移除
delete target[key]
if (!ob) {
return
}
// 通知更新
ob.dep.notify()
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value: Array<any>) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
}
3、Dep
Dep作为Observer和Watcher的中介,用于收集依赖和发送通知。当触发响应式元素的getter时,通过depend()
方法,把自己添加到watcher的依赖;当触发响应式元素的setter时,通过notify()
方法给Dep下的所有Watcher发送通知。
/* @flow */
import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'
let uid = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*
* 可观察对象,可以被多个指令订阅。
*/
export default class Dep {
static target: ?Watcher;
id: number; // 自增的ID
subs: Array<Watcher>; // 订阅者
constructor () {
this.id = uid++
this.subs = []
}
// 添加订阅者
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 移除订阅者
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 把自己添加到target的依赖项
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 通知
notify () {
// stabilize the subscriber list first
// 备份一份subs,因为this.subs可能会发生变化
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
// 按照ID排序
subs.sort((a, b) => a.id - b.id)
}
// 所有的订阅者更新
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
// 全局唯一的,因为一次只能评估一个观察者
// 为了避免某些操作触发响应式属性的getter,重复收集依赖。
// 比如:callHook(),在调用生命周期方法时,可能会获取data的值。
Dep.target = null
// target栈,用于target回退
const targetStack = []
// target入栈
export function pushTarget (target: ?Watcher) {
targetStack.push(target)
Dep.target = target
}
// target出栈
export function popTarget () {
targetStack.pop()
Dep.target = targetStack[targetStack.length - 1]
}
4、Watcher
监听器Watcher 作为订阅者。当dep调用depend方法时,通过addDep()
把当前watcher添加到dep的subs订阅者列表;当dep调用notify方法时,通过update()
执行Watcher的getter(渲染Watcher,会调用vm._update,触发页面更新)和cb回调函数。
/* @flow */
import {
warn,
remove,
isObject,
parsePath,
_Set as Set,
handleError,
invokeWithErrorHandling,
noop
} from '../util/index'
import { traverse } from './traverse'
import { queueWatcher } from './scheduler'
import Dep, { pushTarget, popTarget } from './dep'
import type { SimpleSet } from '../util/index'
let uid = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*
* 监听器Watcher
*
*/
export default class Watcher {
vm: Component; // Vue组件实例
expression: string; // 表达式
cb: Function; // 回调函数
id: number; // 自增ID
deep: boolean; // 深度监听,会递归遍历对象
user: boolean; // 用户自定义,通过$watch添加的监听器
lazy: boolean; // 懒监听,不会立即调用
sync: boolean; // 同步,update方法会立即执行run
dirty: boolean; // 懒监听时,update方法会把dirty置为true,evaluate执行完毕后,才会置为false
active: boolean; // 是否激活。创建时为true,teardown后为false
deps: Array<Dep>; // 已存在的dep集合
newDeps: Array<Dep>; // 新添加的dep集合
depIds: SimpleSet; // 已存在的depId集合
newDepIds: SimpleSet; // 新添加的depId集合
before: ?Function; // 在执行run之前的方法
getter: Function; // 获取数据的方法,由expOrFn转变而来
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
// 标记用于渲染的Watcher
// 每个组件实例都对应一个渲染watcher实例
if (isRenderWatcher) {
vm._watcher = this
}
// 加入到vm的_watchers队列
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} 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()
// 把方法转成string
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
// 解析expOrFn,给getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
// 'a.b.c'格式解析函数
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
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
)
}
}
// 非lazy,立即get
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
* 执行getter,并重新收集依赖
*/
get () {
// 此watcher入栈,添加数据劫持时,把数据的dep,加入到该watcher
pushTarget(this)
let value
const vm = this.vm
try {
// 执行getter,获取值
value = this.getter.call(vm, vm)
} catch (e) {
// 抛出异常
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
// 深入监听,递归遍历
if (this.deep) {
traverse(value)
}
// watcher出栈
popTarget()
// 清空deps
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
* 添加依赖到此指令
*/
addDep (dep: Dep) {
const id = dep.id
// 根据ID判断,dep是否已在此watcher中
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
// dep添加此监听器
dep.addSub(this)
}
}
}
/**
* Clean up for dependency collection.
* 清空依赖集合
*/
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
// 清除dep里面的此监听器
dep.removeSub(this)
}
}
// 把newDepIds交换到depIds
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
// 清空newDepIds
this.newDepIds.clear()
// 把newDeps交换到deps
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
// 清空newDeps
this.newDeps.length = 0
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*
* 当依赖改变时调用
* 用于Dep的notify方法通知更新,以及$forceUpdate强制更新
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
// 懒监听,不执行,设置dirty为true
this.dirty = true
} else if (this.sync) {
// 指定同步执行时,直接调用run方法
this.run()
} else {
// 把此Watcher加入观察者队列,等待更新
queueWatcher(this)
}
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*
* 给调度任务Scheduler调用
*/
run () {
if (this.active) {
// 获取值,执行expOrFn(渲染Watcher,会调用vm._update,触发页面更新)
const value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// 值发生了变化、深度监听
// set new value
const oldValue = this.value
// 赋新值,触发setter,页面更新
this.value = value
// 触发回调,传出新值value和旧值oldValue
if (this.user) {
const info = `callback for watcher "${this.expression}"`
invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*
* 获取watcher的value
* 仅lazy时使用
*/
evaluate () {
this.value = this.get()
// 执行完毕,设置dirty为false
this.dirty = false
}
/**
* Depend on all deps collected by this watcher.
* 调用此watcher收集的所有deps的depend方法
*/
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
/**
* Remove self from all dependencies' subscriber list.
* 移除所有监听器依赖
*/
teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
// 从vm的监听器列表中移除自己,是一个比较昂贵的操作
// 如果vm正在被销毁,那么跳过此步骤
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
// 从所有的deps中移除此Watcher
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
// 设置非激活
this.active = false
}
}
}
5、Array劫持
通过劫持Array的一些方法push, pop, shift, unshift, splice, sort, reverse
(自身数组会发生变化),然后在new Oberver时,替换响应式数组的_proto_或者定义隐藏属性。
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
// 自身数组会发生变化的数组方法
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator (...args) {
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
6、traverse
递归遍历val以调用所有转换的getter ,这样对象中的每个嵌套属性都作为deep依赖项收集。
/* @flow */
import { _Set as Set, isObject } from '../util/index'
import type { SimpleSet } from '../util/index'
import VNode from '../vdom/vnode'
const seenObjects = new Set()
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*
* 递归遍历val以调用所有转换的getter
* 这样对象中的每个嵌套属性都作为deep依赖项收集。
*/
export function traverse (val: any) {
_traverse(val, seenObjects)
seenObjects.clear()
}
function _traverse (val: any, seen: SimpleSet) {
let i, keys
const isA = Array.isArray(val)
// 非数组非Object、已冻结、VNode节点,直接跳出
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
// 存在Observer监听器
if (val.__ob__) {
// 把Dep的id缓存到seenObjects
// 会触发getter
const depId = val.__ob__.dep.id
if (seen.has(depId)) {
return
}
seen.add(depId)
}
if (isA) {
// 数组递归
i = val.length
while (i--) _traverse(val[i], seen)
} else {
// 对象递归
keys = Object.keys(val)
i = keys.length
while (i--) _traverse(val[keys[i]], seen)
}
}
7、scheduler
Watcher的任务调用方法
/* @flow */
import type Watcher from './watcher'
import config from '../config'
import { callHook, activateChildComponent } from '../instance/lifecycle'
import {
warn,
nextTick,
devtools,
inBrowser,
isIE
} from '../util/index'
export const MAX_UPDATE_COUNT = 100
// 调度任务的一些状态
const queue: Array<Watcher> = [] // Watcher队列
const activatedChildren: Array<Component> = [] // 通过keep-alive缓存的组件
let has: { [key: number]: ?true } = {} // 根据ID,判断Watcher是否加入过Watcher
let circular: { [key: number]: number } = {} // Watcher循环统计
let waiting = false // 是否正在等待
let flushing = false // 是否正在刷新
let index = 0 // 正在刷新的索引
/**
* Reset the scheduler's state.
*
* 重置调度程序的状态
*/
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0
has = {}
if (process.env.NODE_ENV !== 'production') {
circular = {}
}
waiting = flushing = false
}
// Async edge case #6566 requires saving the timestamp when event listeners are
// attached. However, calling performance.now() has a perf overhead especially
// if the page has thousands of event listeners. Instead, we take a timestamp
// every time the scheduler flushes and use that for all event listeners
// attached during that flush.
// 刷新时间搓
export let currentFlushTimestamp = 0
// Async edge case fix requires storing an event listener's attach timestamp.
// 获取当前时间搓
let getNow: () => number = Date.now
// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res (relative to page load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
// All IE versions use low-res event timestamps, and have problematic clock
// implementations (#9632)
if (inBrowser && !isIE) {
const performance = window.performance
if (
performance &&
typeof performance.now === 'function' &&
getNow() > document.createEvent('Event').timeStamp
) {
// if the event timestamp, although evaluated AFTER the Date.now(), is
// smaller than it, it means the event is using a hi-res timestamp,
// and we need to use the hi-res version for event listener timestamps as
// well.
// 使用高版本的时间戳获取方法
getNow = () => performance.now()
}
}
/**
* Flush both queues and run the watchers.
* 刷新队列,并且运行监听器
*/
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
// 刷新队列前,先排序。为了确保:
// 1. 父组件总是在子组件之前创建
// 2. 用户添加的Watcher在render的Watcher创建
// 3. 父组件在运行期间被销毁,子组件的Watcher将跳过
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
// 不要缓存queue的长度,因为它可能会添加Watcher
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
// 有before函数,则运行before
if (watcher.before) {
watcher.before()
}
id = watcher.id
// 清空has里面的标记
has[id] = null
// 执行watcher的run方法,触发监听的回调,传出新值和旧值
watcher.run()
// in dev build, check and stop circular updates.
// 开发环境中,检查并停止循环更新。
// 在watch中,修改监听的值,就会进入这样的循环。
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
}
}
}
// keep copies of post queues before resetting state
// 重置之前保存副本
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
// 刷新过后重置状态
resetSchedulerState()
// call component updated and activated hooks
// 触发activated钩子
callActivatedHooks(activatedQueue)
// 触发updated钩子
callUpdatedHooks(updatedQueue)
// devtool hook
// devtool钩子
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
}
function callUpdatedHooks (queue) {
let i = queue.length
while (i--) {
const watcher = queue[i]
const vm = watcher.vm
// 渲染Watcher,已挂载,没有被销毁
if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'updated')
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
* 通过Keep-Alive缓存的组件
*/
export function queueActivatedComponent (vm: Component) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
// 标记未缓存
vm._inactive = false
activatedChildren.push(vm)
}
// 触发activated钩子
function callActivatedHooks (queue) {
for (let i = 0; i < queue.length; i++) {
// 标记组件已被缓存
queue[i]._inactive = true
activateChildComponent(queue[i], true /* true */)
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*
* 把Watcher放入queue
*/
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
// 根据ID判断是否重复加入过Watcher队列的,已加入的则跳过
if (has[id] == null) {
// 标记此Watcher加入
has[id] = true
if (!flushing) {
// 不是正在刷新,把此Watcher放入queue
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
// 如果正在刷新,则把Watcher插入到未刷新的区间
// 规则:index到queue.length - 1区间 表示未刷新的、比较靠后的Watcher,
// 根据此Watcher的id应该插入的位置,刷新中的queue是按照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
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
// 等待dom更新完毕之后,再执行flushSchedulerQueue
nextTick(flushSchedulerQueue)
}
}
}