前言
observer应该是Vue的一个核心模块,也即是Vue的响应式原理。主要通过底层的Object.defineProperty
,来定义属性的getter/setter
来实现。
每个组件实例都有相应的watcher
实例对象,它会在组件渲染的过程中把属性记录为依赖,之后当依赖项的 setter 被调用时,会通知 watcher 重新计算,从而致使它关联的组件得以更新。
正文
源码的版本是:version: 2.5.13
, 当前的源码是用flow.js
写的
Observer的整体结构大概是这样的
我们写个简单的App.vue
<template>
<div id="app">
<div>
count: {{count}}
<button @click='add'>+</button>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
count: 0
}
},
methods: {
add () {
this.count++
}
}
}
</script>
data的count会渲染到使视图中,而点击button时,count会添加1,并更新到视图中。这就是响应式,当count修改的时候,就是通知视图去更新;
我们先从Vue怎么初始化data说起
// core/instance/state.js
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
// 代理这些函数, this[key] = this._data[key]
proxy(vm, `_data`, key)
}
}
// observe data
// 观察data
observe(data, true /* asRootData */)
}
初始化data,主要作用是代理了data的这些属性,this[key] = this._data[key]
,所以我们可以通过this[key]
来获取和赋值。
再转移到observe
函数的实现
// core/observer/index.js
export function observe (value: any, asRootData: ?boolean): Observer | void {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
这段主要new
一个Observer
实例,已经存在的就不用
// core/observer/index.js
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that has this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
const augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i], 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])
}
}
}
该实例有3个属性,value
,dep
,vmCount
。value
也就是我们赋予它的初始值;dep
是一个Dep
实例,我们待会再看它的具体实现。我把它当成一个发布者,等待watcher
来订阅; 最后形成依赖关系;def(value, '__ob__', this)
,则主要是在value
中添加一个__ob__
属性,指向this
我们讲讲上面这段代码constructor
方法判断了value
是否为数组,是的话就Observe a list of Array items
;
最后都会经过walk,重新定义data的属性,转化为响应式属性
我们先看Dep的实现,后面才能更好的讲解defineReactive
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)
}
// 订阅,当前watcher添加到subs当中
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 通知到每个subs执行update
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
const targetStack = []
export function pushTarget (_target: Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
export function popTarget () {
Dep.target = targetStack.pop()
}
subs
就是存储watcher
(订阅者)的Dep.target
的值就是当前的watcher
depend()
形成依赖关系,把当前的watcher
添加进subs
中;notify()
,相当于发布,通知所有的订阅者(watcher
)执行update
我们再来看defineReactive
// core/observer/index.js
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
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
},
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()
}
})
}
这里形成了闭包,每个属性都有一个dep
实例,会一直存在,供get
,set
调用get
方法中,我们已经知道Dep.target
就是一个watcher
,当Dep.target
存在的时候,就会把当前的Dep.target
加入到dep
实例的subs
当中,形成依赖关系set
方法判断是否跟之前的value
相同,不相同则执行dep.notify()
,通知所有的订阅者(watcher
)
目前已大致理解清了结构;
把data的属性遍历,转换为响应式属性,重新定义它的getter/setter
。dep
来存储依赖关系并作为发布者的角色,watcher
相当于订阅者getter
获取值的时候,主要用于形成依赖,把当前的watcher
加入到需要的属性的dep当中,形成依赖。setter
修改值的时候,通过dep形成的依赖,通知所有订阅了该属性的watcher
最后我们看看watcher
的实现
// core/observer/watcher.js
export default class Watcher {
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this
}
// 把this加入到组件的_watcher当中
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.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 = 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()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
// Dep.target赋值为当前实例
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 {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
*/
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)
}
}
}
/**
* 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) {
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)
}
}
}
}
}
当lazy
为false
的时候,也就是不是懒加载的时候,立即执行get()
pushTarget(this)
把Dep.target赋值为当前实例watcherthis.getter
就是我们传入的参数expOrFn
,它就是来收集依赖的,通过执行里面的函数,获取属性this[key]
来执行我们重新定义的响应式属性的getter
,形成依赖关系。(不懂的可以回顾defineReactive
)。
修改响应式属性的时候,通知订阅了该属性的watcher
去触发update()
,如果是同步的,立刻执行run()
,否则加入到queueWatcher
;run()
中const value = this.get()
会触发this.getter
,并且重新更新依赖关系
例如组件在mounted
生命周期的时候,里面会创建一个watcher实例,也就是我们所说的每个组件都会创建一个watcher实例。new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)
,updateComponent里面需要获取一些需要的响应式属性this._data[key]
,触发属性的getter
,最后形成依赖关系。
修改订阅了的属性的时候,通知该watcher
去update()
,最后执行run()
。run()
中执行updateComponent
,以达到重新更新视图的效果,并重新获取依赖关系
自己再举个例子:
function getter(){
return this.a + this.b;
}
const w1 = new Watcher(vm, getter, noop, null);
执行getter
的时候,就是为了获取this.a
和this.b
的值,而a
和b
属性已经在defineReactive
中重新定义,获取就会属性的触发getter
,最后获取形成依赖关系。
当我们要修改a的时候, this.a = 2
,就是通知订阅了该属性的w1
, 执行w1.update()
, 最后run
中再执行getter
函数,并且重新获取依赖。
理清楚这个例子也就差不多理解这个整个过程了。