Vue中的响应式
Vue的响应式是Vue最重要的特性之一,Vue的数据响应主要是通过 观察者模式(Observer Pattern) 实现,所谓的观察者模式,即定义【数据】和【视图中数据的使用对象】的一对多的依赖关系。当一个对象(目标对象)的状态发生改变时,所有依赖于它的对象(观察者对象)都得到通知并被自动更新。
应用举例:
在应用中,在A组件、B组件、C组件中,分别使用到了日期参数date,这个参数和多个组件的依赖关系可以理解为观察者模式,日期参数date 是目标对象,A组件、B组件、C组件就是观察者对象,当目标属性date的状态改变,观察者会通知所依赖它的组件,这些组件就更新对应的内容。
observe
observe是响应式处理的入口,如果一个对象 value 没有被观察过,则创建一个观察者实例:ob = new Observer(value) 来对数据进行观察,observe函数最终返回一个被观察对象的实例。
observe 函数接收两个参数,第一个参数是要观测的数据,第二个参数是一个布尔值,代表将要被观测的数据是否是根级数据。
源码所在文件夹:/src/core/observer/index.js
export function observe (value: any, asRootData: ?boolean): Observer | void {
// 如果要观测的数据不是一个对象或者是 VNode 实例,则直接 return
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
// 如果 value 对象上存在 __ob__ 属性,则表示已经做过观察了,直接返回 __ob__ 属性
// 数据对象被观测了该对象上会扩展一个__ob__ 属性
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
) {
// 如果数据对象上没有定义 ob 属性,那么说明该对象没有被观测过
// 创建观察者实例
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
Observer
Vue中定义了一个Observer类,通过Object.defineProperty()方法对数据进行 “劫持”,即给每个属性添加get / set方法,从而让每个属性成为被观察的对象。
Observer是一个观察者类,每个属性都会通过Observer类变成一个被观察对象,并收集依赖和通知更新。
源码所在文件夹:/src/core/observer/index.js
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
// 实例对象的 dep 属性获取Dep构造函数实例的引用,用于依赖收集
this.dep = new Dep()
this.vmCount = 0
// 使用 def 函数,为数据对象定义了一个 ob 属性,
// 这个属性的值就是当前 Observer 实例对象
def(value, '__ob__', this)
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
// 当值为对象时,遍历对象中的每个key,为每个key设置响应式
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
// 当值为数组时,遍历数组里的每个key,为数组里的key设置观察
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
Object.defineProperty()
定义: 通过vm对象来代理data对象中属性的操作(读/写)
优势: 更加方便的操作data中的数据
原理:
- 通过Object.defineProperty()把data对象中所有属性添加到vm上
- 为每一个添加到vm上的属性,都指定一个getter/setter
- 在getter/setter内部去操作(读/写)data中对应的属性
Object.defineProperty(object, propertyname, descriptor)
- object:必须,要在其上添加或修改属性的对象
- propertyname:必需。 一个包含属性名称的字符串
- descriptor: 属性描述符。 它可以针对数据属性或访问器属性
descriptor:有以下参数值
- value: 该属性的值,默认为 undefined
- writable: 该属性是否可写,默认为 false
- configurable: 控制了该属性是否可被改变、是否可删除,默认为false
- enumerable: 该属性是否可枚举,默认为false
- get: 给属性提供 getter 的方法,若是没有 getter 则为 undefined
- set: 给属性提供 setter 的方法,若是没有 setter 则为 undefined
defineReactive
源码所在文件夹:/src/core/observer/index.js
// 拦截 obj[key] 的读取和设置操作
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
// 实例化 dep,一个 key 一个 dep
const dep = new Dep()
// 获取 obj[key] 的属性描述符,发现它是不可配置对象的话直接 return
const property = Object.getOwnPropertyDescriptor(obj, key)
// 如果对象属性的configurable为false时,
// 代表该属性无法被修改,即无法为其增加get/set,直接return
if (property && property.configurable === false) {
return
}
// 记录 getter 和 setter,获取 val 值
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
// 如果value是一个obj,这里会递归的处理,给value的属性添加get/set
let childOb = !shallow && observe(val)
// 响应式核心函数:Object.defineProperty()
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
// Dep.target 为 Dep 类的一个静态属性,值为 watcher,在实例化 Watcher 时会被设置,
// 实例化 Watcher 时会执行 new Watcher 时传递的回调函数(computed 除外,因为它懒执行)
// 而回调函数中如果有 vm.key 的读取行为,则会触发这里的 读取 拦截,进行依赖收集
// 回调函数执行完以后又会将 Dep.target 设置为 null,避免这里重复收集依赖
const value = getter ? getter.call(obj) : val
if (Dep.target) {
// 依赖收集,在 dep 中添加 watcher,也在 watcher 中添加 dep
dep.depend()
// childOb 表示对象中嵌套对象的观察者对象,如果存在也对其进行依赖收集
if (childOb) {
// 这就是 this.key.chidlKey 被更新时能触发响应式更新的原因
childOb.dep.depend()
// 如果是 obj[key] 是 数组,则触发数组响应式
if (Array.isArray(value)) {
// 为数组项为对象的项添加依赖
dependArray(value)
}
}
}
return value
},
// set 拦截对 obj[key] 的设置操作
set: function reactiveSetter (newVal) {
// 旧的 obj[key]
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()
}
// setter 不存在说明该属性是一个只读属性,直接 return
if (getter && !setter) return
// 设置新值
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
// 对新值进行观察,让新值也是响应式的
childOb = !shallow && observe(newVal)
// 依赖通知更新
dep.notify()
}
})
}
Dep
Dep,dependence 的缩写,Dep是负责存放数据对应观察者对象的容器,只要数据发生改变,就会通过这个Dep来通知所有观察者进行修改数据。(每个数据都有独一无二的Dep)。
在Dep类中,有一个subs数组,用于存放所有被收集的依赖(即watcher),将依赖存放在subs中,目的是后面数据发生变化的时候能够通知那些subs做出准备,Dep类中有几个函数:
addSub(): 添加订阅者
removeSub() : 删除订阅者
notify(): 数据改变时触发订阅者的更新操作
depend(): 依赖收集(所谓的依赖其实就是watcher),Dep.target对应的是一个watcher,depend() 方法:对应的watcher调用addDep() 方法将watcher存放到subs数组中。
在defineReactive函数中,每个属性都会通过 const dep = new Dep() 实例化一个dep对象。
源码所在文件夹:/src/core/observer/dep.js
export default 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()
if (process.env.NODE_ENV !== 'production' && !config.async) {
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
Watcher
Watcher是Vue中的观察者类,作用是观察Vue组件中的属性,当属性更新时,通知watcher执行更新dom操作,watcher是一个执行者。
Watcher的三种类型
- 计算属性computed创建的computedWatcher
- 侦听器watch创建的userWatcher
- 渲染更新dom的renderWatcher
一个组件只有一个renderWatcher,有多个computedWatcher和userWatcher
在 vue源码解读(二) -- new vue(options)的过程文章中,我们知道在initSate函数中,处理顺序是
- initProps
- initMethods
- initData
- initComputed
- initWatch
所以组件内创建的watcher顺序是:
- computedWatcher
- userWatcher
- renderWatcher
expOrFn属性可以接收 computedWatcher / userWatcher / renderWatcher三个函数,其中computedWatcher传的是函数, 用于获取computed属性的值,userWatcher 传的是属性名, 通过属性名获取所对应的函数,renderWatcher传的是updateComponent即组件更新函数,最终这三个函数会被保存在watcher.getter中。
Watcher的属性和方法
deps: 表示前一次视图渲染添加的Dep实例数组
depIds: 表示前一次视图渲染时,addDep 过程中,收集的 dep id
newDeps: 表示本次视图渲染新添加的Dep实例数组
newDepIds: 表示本次视图渲染在最新的 addDep过程中,收集的 dep id
get(): 函数的作用是获取对应属性的值,并与观察的属性建立依赖关系,执行流程:
- 将Dep类的静态属性target设置为当前watcher,并推入存储watcher的栈中;
- 执行getter函数,watcher.getter执行期间,只要有读取到属性(已经做过响应式处理的属性),就会建立属性与watcher依赖收集;
- 将Dep类的静态属性target设置为当前watcher,并退出存储watcher的栈;
update(): watcher所观察的属性,触发更新
addDep(): 将当前watcher中没有收集的dep收集到当前watcher中,进行了dep去重
cleanupDeps(): 去除那些前一次渲染被视图依赖本次渲染不被视图依赖的属性,防止前一次渲染的值改变造成视图重新渲染,提升了性能
queueWatcher(): 将watcher去重,然后添加到队列中。然后执行nextTick(flushSchedulerQueue)异步更新
run(): vue执行异步更新时,会遍历触发watcher的run函数,执行get()函数
源码所在文件夹:/src/core/observer/watcher.js
export default 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;
before: ?Function;
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
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()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
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
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
// 打开 Dep.target,Dep.target = this
pushTarget(this)
let value
const vm = this.vm
try {
// 执行回调函数,比如 updateComponent,进入 patch 阶段
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)
}
// 关闭 Dep.target,Dep.target = null
popTarget()
this.cleanupDeps()
}
return value
}
// 1、添加 dep 给自己(watcher)
// 2、添加自己(watcher)到 dep
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)
}
}
}
/**
* 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.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
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
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
this.value = value
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.
*/
evaluate () {
this.value = this.get()
this.dirty = false
}
/**
* Depend on all deps collected by this watcher.
*/
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.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
}
总结
dep 和 watcher 建立联系的过程
- 执行watcher.get函数
- pushTarget(watcher):将Dep.target设置为当前watcher
- 执行watcher.getter,watcher.getter执行期间,只要有读取到属性(已经做过响应式处理的属性),就会建立属性与watcher依赖收集
- 依赖收集过程:
-
- 属性的get函数 会执行dep.depend()
- dep.depend() 会将执行当前Dep.target即watcher的addDep(dep)函数,并传入当前dep
- watcher.addDep:会将dep存入newDeps实例属性上,并调用dep.addSub(watcher),并传入watcher
- dep.addSub:会将传入的watcher存入当前dep的subs实例属性上,然后dep和watcher就互相建立好联系
- watcher.getter执行结束后,会调用popTarget,将Dep.target设置为空