Vue源码阅读连载之响应式设计
书接上回,谈到Vue是在Vue.prototype._init里调用了initState初始化了响应式的组成,看一下initState的源码
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
这里面除了methods,其它像props、data之类的都是响应式的,如果在模板里面引用到了其中某个变量,在变量发生变化的时候会主动通知进而更新DOM。
Object.defineProperty
只要读过官网文档就都知道Vue里响应式设计的基本原理就是这个方法,这个方法在es5里被引入,属于元编程,就是说在之前版本的JavaScript里无法使用既有的语法来对它进行模拟,这也就是Vue无法支持IE9以下的浏览器的原因。
但是Object.defineProperty也有它的缺陷,一些变化还是追踪不到的,比如在对象上新增一个值,delete一个值,以及数组上针对索引直接赋值等,Vue对此提供了$set和$delete方法来补充,后面会讲到。
要真正弥补缺陷,还是要依靠es6的Proxy,但它也是属于元编程。即便是Babel目前也对它无能为力。
所以要等到完美实现自动挡的响应式,还是要让es6得到浏览器的全面支持才行。
看一下Object.defineProperty的用法
Object.defineProperties(obj, props)
其中props可以配置get和set,这样就有了一个切入点能让我来干点什么。
var obj = {};
Object.defineProperty(obj, "data", {
get: function() {
//把依赖收集起来
},
set: function() {
//通知依赖要更新了
}
})
所以可以抽象出一个依赖的对象来,叫Dep,此时可以把Object.defineProperty重新封装一下,在/src/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
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
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
// #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()
}
})
}
这个方法里有一个Dep对象,在get的时候就更新这个Dep对象实例维护的依赖数组,在set的时候就通知Dep对象里的依赖数组去执行更新。
这里看不懂没关系,一直往下走,走到框图那里就好了,到时候记得再回来看代码。
Dep和Watcher
Dep对象的定义在/src/core/observer/dep.js
/* @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;
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 () {
// stabilize the subscriber list first
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
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.
Dep.target = null
const targetStack = []
export function pushTarget (target: ?Watcher) {
targetStack.push(target)
Dep.target = target
}
export function popTarget () {
targetStack.pop()
Dep.target = targetStack[targetStack.length - 1]
}
这里先记住结论,Dep就是一个中间商。Dep实例里面还有一个叫Watcher的对象。这个Watcher对象的定义在/src/core/observer/watcher.js里
let uid = 0
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 () {
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)
}
}
}
/**
* 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) {
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)
}
}
}
}
/**
* 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
}
}
}
代码贴的有点敷衍[流汗]
其实Watcher对象就代表了一个响应式的内容,比如模板的{{ }}标记,在{{ }}标记里引用到的变量发生变化时更新DOM,或者某一个computed变量,在它引用到的变量发生变化时进行重新计算,如果它也是被{{ }}标记绑在模板上的话进而触发DOM的更新,还有就是在创建Vue时传入显式定义的watch了,它跟computed也是类似的。
更正:其实Vue2.0后用了虚拟DOM,所以不会为每一个模板中使用到的变量创建一个Watcher而是整个组件创建一个Watcher,剩下比较的事情就交给虚拟DOM了。
其实可以在源码里全局搜索一下"new Watcher"关键词,总共也就是四处
Watcher对象和Dep对象里都含有一个属性互相指向了对方,Dep里是subs,Watcher里是deps。
流程
重新再捋一下流程,以模板上用到props里的message为例
- 新建Vue时,传入配置,其中props里包含这个message
- 在调用initProps时,在Vue实例上新建一个内部的空对象_props
- 经过defineReactive之后,这个props里的message转为_props其中的一个对象,这个对象还有get和set方法
- 为虚拟DOM的组件新建一个Watcher对象
- 在新建Watcher对象的构造函数里,会去取一下message的值,这样就触发了get
- 在get里把Watcher对象跟Dep对象关联了起来
- 下一次更新props里message的时候就触发了set,从而更新了DOM
再仔细地走一下,
new Vue( ) → Vue.prototype._init( ) → initState( ) 其中
if (opts.props) initProps(vm, opts.props)
就去初始化props,先建出内部_props空对象,然后循环把props里面内容都通过defineReactive包装为 _props的一个属性,这个属性包含了get和set。
function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = []
const isRoot = !vm.$parent
// root instance props should be converted
if (!isRoot) {
toggleObserving(false)
}
for (const key in propsOptions) {
keys.push(key)
const value = validateProp(key, propsOptions, propsData, vm)
defineReactive(props, key, value)
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
toggleObserving(true)
}
等到模板解析的时候发现用到了这个message,于是去新建一个Watcher对象,在它的构造函数最后有调用
this.value = this.lazy
? undefined
: this.get()
而get( )里就去获得这个值
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 {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
注意一下pushTarget和popTarget两个方法,它是把当前的Watcher对象放入Dep.target上,注意这个是Dep,也就是类,不是Dep的实例,这样保证了唯一性,反正JavaScript里是单线程的。this.getter在构造函数里被声明为
this.getter = parsePath(expOrFn)
也就是针对表达式的解析,比如"data.x.y.z"这种样子的,
value = this.getter.call(vm, vm)
这一句就能获得这个表达式的值,也就相当于访问了data.x.y.z。
既然访问了这个属性,那么就触发了这个属性上的get,从而把Dep和Watcher建立起连接来,等到下一次触发set的时候自然也就能找到这个属性上挂载的所有的Watcher,从而得到更新。