Vue.js实现响应式的核心是利用了es5的object.defineProperty,这也是vue.js不能兼容ie8及以下浏览器的原因。
Object.defineProperty
Object.defineProperty方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回这个对象,看下它的语法:
Object.defineProperty(obj,prop,descriptor)
obj是要在其上定义属性的对象;prop是要定义或修改的属性的名称;descriptor是将被定义或修改的属性描述符。descriptor里有很多可选键值,我们最关心的是get和set,get是一个给属性提供的getter方法,当我们访问了该属性的时候会触发getter方法;set是一个给属性提供的setter方法,当我们对该属性做修改的时候会触发setter方法。一旦对象拥有了getter和setter,我们可以简单地把这个对象称为响应式对象。
initState
在Vue的初始化阶段,_init方法执行的时候,会执行initState(vm)方法,它的定义在src/core/instance/state.js中。
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)
}
}
initState方法主要是对props、methods、data、computed和watcher等属性做了初始化操作。这里我们重点分析下props和data,
initProps
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)
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
const hyphenatedKey = hyphenate(key)
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
defineReactive(props, key, value, () => {
if (vm.$parent && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
)
}
})
} else {
defineReactive(props, key, value)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
toggleObserving(true)
}
props的初始化主要过程,就是遍历定义的props配置。遍历的过程主要做两件事,一是调用defineReactive方法把每个prop对应的值变成响应式,可以通过vm._props.xxx访问到定义props中对应的属性。另一个是通过proxy把vm._props.xxx的访问代理到vm.xxx上。
initData
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)) {
proxy(vm, `_data`, key)
}
}
// observe data
observe(data, true /* asRootData */)
}
拿到option.data赋值给vm._data变成一个对象,然后遍历所有的keys值,然后在某些情况下报一些警告,然后把_data上的东西代理到我们的vm实例上。另外调用observe观测整个data的变化,把data也变成响应式,可以通过vm._data.xxx访问到定义data返回函数中对应的属性。
proxy
代理的作用是把props和data上的属性代理到vm实例上,这也就是为什么我们定义了如下props,却可以通过vm实例访问到它。
let test = {
props:{
msg:'hello world'
},
methods:{
getTest(){
console.log(this.msg)
}
}
}
我们在getTest函数中通过this.msg访问到我们定义的props中的msg,这个过程发生在proxy阶段:
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
通过Object.defineProperty把target[sourceKey][key]的读写变成了对target[key]的读写。所以对于props而言,对vm._props.xxx的读写变成了vm.xxx的读写,而对于vm.xxx访问定义在props中的xxx属性了。同理对于data而言,对vm._data.xxxx的读写变成了对vm.xxxx的读写,而对于vm._data.xxxx的读写,我们可以访问到定义在data函数返回对象中的属性,所以我们就可以通过vm.xxxx访问到定义在data函数返回对象中的xxxx属性了。
observe
observe的功能就是用来监测数据的变化,它的定义在src/core/observer/index.js中:
/**
* 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.
*/
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 (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
observe接收两个值,一个是value,任意类型的一个是asRootData,在initData中调用observe
observe(data,true)
传入的是定义的data的这个对象,然后调用observe这个函数后,先判断value是不是一个object,如果是一个object并且是一个VNode,这两个条件都满足的情况下,直接返回。接着判断value是否有__ob__这个属性,如果有的话并且是Observer这个实例, 直接拿到ob并且返回,否则的话判断几个条件,第一个是shouldObserve,这个shouldObserve在全局中定义了
export let shouldObserve: boolean = true
export function toggleObserving (value: boolean) {
shouldObserve = value
}
shouldObserve会通过toggleObserving这个方法来修改值。第二个是!isServerRendering()并且要么是一个数组要么是一个对象,并且是这个对象是可扩展的一些属性,最后还要判断它不是一个vue, 满足了以上这些个条件才会去实例化observe。
Observer
Observer是一个类,它的作用是给对象的属性添加getter和setter,用于依赖收集和派发更新
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])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
new Observe的时候会执行这个构造函数,然后保留这个value,实例化Dep,然后调用def,
/**
* Define a property.
*/
export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
})
}
def呢就是把Object.defineProperty做一次封装。在这里它的目标呢是给value,添加一个__ob__属性,并且这个属性的值呢指向当前的这个实例,然后对value进行判断是否是数组,然后调用observeArray方法
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
遍历数组中的每个元素,然后递归调用observe。
如果数组是一个对象,就会调用walk方法,
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
walk方法呢很简单,遍历对象上的所有属性,然后调用defineReactive
defineReactive
defineReactive的功能就是定义一个响应式对象,给对象动态添加getter和setter,
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
}
/* 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()
}
})
}
defineReactive函数最开始初始化Dep对象的实例,接着拿到obj的属性描述符,然后对子对象递归调用observe方法,这样就保住了无论obj的结构多复杂,它的所有子属性也能变成响应式的对象,这样我们访问或修改obj中一个嵌套较深的属性,也能触发getter和setter。最后利用Object.defineProperty去给obj的属性key添加getter和setter。 我们来分析下getter的逻辑,getter的过程呢就是完成了依赖收集。首先拿到这个getter,然后去进行getter.call,如果没有的话就直接用这个val值,然后一段依赖的过程,首先判断Dep.target是否存在,Dep呢是一个类,我们来看下,
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()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
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()
}
主要功能是建立数据和watcher之间的桥梁。Dep.target是一个全局的watcher,因为同一时间只有一个watcher会被计算,所以target表明了我当前正在被计算的watcher。Dep除了静态的target属性还有两个,id,subs,我们每创建一个Dep,id都是自增的,subs就是所有的watcher。
Dep实际上就是对watcher的一种管理,Dep脱离wathcer单独存在是没有意义的,我们看一下wathcer的一些相关实现,
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.
*/
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
computed: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
dep: Dep;
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.computed = !!options.computed
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.computed = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.computed // for computed 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 = 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
)
}
}
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
this.value = 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
}
...
}
watcher是一个Class,在它的构造函数中,定义了一些和Dep相关的属性:
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
其中,this.deps和this.newDeps表示watcher实例持有的Dep实例的数组;而this.depIds和this.newDepIds分别代表this.deps和this.newDeps的idSet。 在Vue的mount过程是通过mountComponent函数,
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
当我们去实例化一个渲染watcher的时候,首先进入watcher的构造函数逻辑,然后会执行它的this.get()方法,进入get函数,首先会执行:
pushTarget(this)
pushTarget的定义在src/core/observer/dep.js中:
export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
实际上就是把Dep.target赋值为当前的渲染watcher并压栈,接着又执行了:
value = this.getter.call(vm, vm)
this.getter对应就是updateComponent函数,这实际上就是在执行:
vm._update(vm._render(),hydrating)
它会先执行vm._render()方法,因为之前分析过这个方法会生成渲染VNode,并且在这个过程中会对vm上的数据访问,这个时候就触发了数据对象的getter。那么每个对象值的getter都持有一个dep,在触发getter的时候会调用dep.depend()方法,也就会执行Dep.target.addDep(this)。 刚才Dep.target已经被赋值为渲染watcher,那么就执行到addDep方法:
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)
}
}
}
这时候做了一些逻辑判断然后执行dep.addSub(this),那么就会执行this.subs.push(sub),也就是说把当前的watcher订阅到这个数据持有的dep的subs中,这个目的是为后续数据变化时候能通知到哪些subs做准备的。 所以在vm._render()过程中,会触发所有数据的getter,这样实际上已经完成了一个依赖收集的过程。再完成依赖收集后,还有执行
if(this.deep){
traverse(value)
}
这个是要递归去访问value,触发它所有子项的getter,接下来执行
popTarget()
popTarget的定义在src/core/observer/dep.js中
Dep.target = targetStack.pop()
实际上就是把Dep.target恢复和成上一个状态,因为当前vm的数据依赖收集已经完成,所以对应的渲染Dep.target也需要改变。最后执行:
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
}
考虑到Vue是数据驱动的,所以每次数据变化都会重新render,那么vm._render()方法又会再次执行,并再次触发数据的getters,所以watcher在构造函数中会初始化2个Dep实例数组,newDeps表示新添加的Dep实例数组,而deps表示上一次还有加的Dep实例数组。 在执行cleanupDeps函数的时候,会首先遍历deps,移除对dep的订阅,然后把newDepIds和depIds交换,newDeps和deps交换,并把newDepIds和newDeps清空。 那么为什么需要做deps访问的移除呢,在添加deps的订阅过程,已经能通过id去重避免重复订阅了。 考虑一种场景,例如:我们用v-if去渲染不同子模板a、b,当我们满足某条件渲染a的时候,会访问到a中的数据,这时候我们对a使用的数据添加了getter,做了依赖收集,那么当我们去修改a的数据的时候,理应通知到这些订阅者。那么一旦我们改变了条件渲染了b模板,又会对b使用的数据添加了getter,如果我们没有依赖移除的过程,那么这时候我去修改a模板的数据,会通知a数据的订阅的回调,这显然是有浪费的。 所以Vue设计了在每次添加完新的订阅,会移除掉旧的订阅,这样就保证了在我们刚才的场景中,如果渲染b模板的时候去修改a模板的数据,a数据订阅回调已经被移除了,所以不会有任何浪费。