響應(yīng)式原理
Vue實(shí)現(xiàn)響應(yīng)式的核心是利用了Object.defindProperty
為對(duì)象的屬性添加getter和setter方法洒闸,接下來(lái)我們從源碼層面來(lái)看具體的實(shí)現(xiàn)方式
initState
Vue在初始化的過(guò)程中會(huì)調(diào)用initState
方法染坯,他定義在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
方法對(duì)vm.$options
中的props
, methods
,data
,computed
,watch
這些屬性做了初始化操作。
-
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)
}
initProps
方法對(duì)props中的每一個(gè)key調(diào)用了defineReactive
方法丘逸,然后調(diào)用proxy
方法將屬性代理到vm實(shí)例上单鹿。
-
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 */)
}
`initData`方法在開(kāi)發(fā)環(huán)境下檢查data中的屬性是否已經(jīng)在props和methods里重復(fù)定義,然后調(diào)用
`proxy`方法將這些屬性代理到vm實(shí)例上深纲。最后調(diào)用`observe`方法
那么我們重點(diǎn)看一下`observe`方法和`defindReactive`方法做了什么
## `observe`
`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 (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
`observe`方法為非VNode的對(duì)象類(lèi)型值添加了一個(gè)`Observer`對(duì)象仲锄,`Observer`的定義:
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])
}
}
}
`Observer`的構(gòu)造函數(shù)創(chuàng)建了一個(gè)`Dep`對(duì)象,然后通過(guò)`def(value, '__ob__', this)`將這個(gè)對(duì)象的`__ob__`屬性設(shè)置為自身湃鹊,這會(huì)使`__ob__`屬性的descriptor中的`enumerable`為false儒喊。接下來(lái)調(diào)用`walk`方法對(duì)這個(gè)對(duì)象的每一個(gè)屬性調(diào)用`defineReactive`方法。
## `defineReactive`
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`的作用是將對(duì)象上的一個(gè)屬性定義為響應(yīng)式屬性币呵,它的邏輯也十分清晰怀愧。首先創(chuàng)建了一個(gè)`Dep`對(duì)象,然后對(duì)這個(gè)屬性的值遞歸地調(diào)用`observe`方法余赢,使這個(gè)屬性的值也成為響應(yīng)式的芯义,最后用`Object.defineProperty`為這個(gè)屬性的descriptor定義了`get`和`set`方法
## getter
我們來(lái)看getter部分的邏輯,它會(huì)調(diào)用`dep.depend()`方法妻柒,那么我們首先來(lái)看`Dep`是什么扛拨。
### Dep
`Dep`的定義是在`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 () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
`Dep`表示dependence,它是用來(lái)記錄有那些組件依賴(lài)了特定的屬性举塔。每個(gè)響應(yīng)式的屬性都有一個(gè)Dep對(duì)象鬼癣,Dep對(duì)象的`subs`屬性就表示subscript陶贼,訂閱。`subs`數(shù)組中放的是`Watcher`類(lèi)型的值待秃。
### `Watcher`
`Watcher`的定義在`core/observer/watcher.js`拜秧,代碼太長(zhǎng)就不貼了。
`Watcher`的構(gòu)造函數(shù)定義了一些`Dep`的數(shù)組
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
// ...
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
this.value = this.get()
}
如果不是計(jì)算屬性章郁,`Watcher`的構(gòu)造函數(shù)最后調(diào)用了`this.get()`方法枉氮。
### 流程
`Watcher`的創(chuàng)建是在Vue掛載的時(shí)候,在`mountComponent`方法中有這么一段邏輯:
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
// ...
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
當(dāng)一個(gè)組件掛載的時(shí)候暖庄,創(chuàng)建`Watch`聊替,執(zhí)行`this.get()`方法,首先調(diào)用
pushTarget(this)
pushTarget 的定義在 src/core/observer/dep.js 中:
···
export function pushTarget (_target: Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
···
就是講當(dāng)前的`Dep.target`入棧培廓,然后將`Dep.target`設(shè)置為當(dāng)前的watcher惹悄。接著執(zhí)行了
value = this.getter.call(vm, vm)
`this.getter`也就是傳入的`updateComponent`方法,對(duì)組件進(jìn)行了一次渲染更新肩钠。在渲染更新的時(shí)候會(huì)訪問(wèn)到vm上的數(shù)據(jù)泣港,也就調(diào)用了響應(yīng)式屬性的getter,getter中會(huì)調(diào)用`dep.depend()`
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
又調(diào)用了`Dep.target.addDep(this)
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)
}
}
}
`addDep`方法檢查了dep是否重復(fù)价匠,如果沒(méi)有重復(fù)就將這個(gè)dep添加到`this.newDeps`數(shù)組当纱,并且經(jīng)這個(gè)watcher添加到dep的subs數(shù)組中
`updateComponet`的過(guò)程中會(huì)觸發(fā)所有數(shù)據(jù)的getter,也就完成了一個(gè)依賴(lài)收集過(guò)程踩窖,記錄了當(dāng)數(shù)據(jù)發(fā)生變化坡氯,有哪些組件需要更新。
最后洋腮,`Watcher`的`get()`方法執(zhí)行了
popTarget()
this.cleanupDeps()
將Dep.Target恢復(fù)成父級(jí)組件的Watcher箫柳,并清空已經(jīng)不再依賴(lài)的數(shù)據(jù)的Dep
## setter
設(shè)置響應(yīng)式屬性的值的時(shí)候,它的setter會(huì)被調(diào)用啥供。
setter的邏輯有這么幾點(diǎn):
1. 如果舊的值和新的值相等或都是NaN滞时,則返回
2. 調(diào)用
childOb = !shallow && observe(newVal)
遞歸地將為新值添加getter/setter
3. 調(diào)用
dep.notify()
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
調(diào)用每個(gè)訂閱此屬性的Watcher的`update`方法
class Watcher {
// ...
update () {
/* istanbul ignore else */
if (this.computed) {
// A computed property watcher has two modes: lazy and activated.
// It initializes as lazy by default, and only becomes activated when
// it is depended on by at least one subscriber, which is typically
// another computed property or a component's render function.
if (this.dep.subs.length === 0) {
// In lazy mode, we don't want to perform computations until necessary,
// so we simply mark the watcher as dirty. The actual computation is
// performed just-in-time in this.evaluate() when the computed property
// is accessed.
this.dirty = true
} else {
// In activated mode, we want to proactively perform the computation
// but only notify our subscribers when the value has indeed changed.
this.getAndInvoke(() => {
this.dep.notify()
})
}
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
}
如果不是計(jì)算屬性獲知this.sync為false,就會(huì)調(diào)用`queWatcher(this)`
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
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.
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
nextTick(flushSchedulerQueue)
}
}
}
`queueWatcher`將watcher加入到一個(gè)隊(duì)列滤灯,在nextTick調(diào)用`flushSchedulerQueue`
function flushSchedulerQueue () {
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.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
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
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
}
`flushSchedulerQueue`首先按照id從小到大對(duì)隊(duì)列中的watcher進(jìn)行排序坪稽,這么做是為了要確保以下幾點(diǎn):
1.組件的更新由父到子;因?yàn)楦附M件的創(chuàng)建過(guò)程是先于子的鳞骤,所以 watcher 的創(chuàng)建也是先父后子窒百,執(zhí)行順序也應(yīng)該保持先父后子。
2.用戶(hù)的自定義 watcher 要優(yōu)先于渲染 watcher 執(zhí)行豫尽;因?yàn)橛脩?hù)自定義 watcher 是在渲染 watcher 之前創(chuàng)建的篙梢。
3.如果一個(gè)組件在父組件的 watcher 執(zhí)行期間被銷(xiāo)毀,那么它對(duì)應(yīng)的 watcher 執(zhí)行都可以被跳過(guò)美旧,所以父組件的 watcher 應(yīng)該先執(zhí)行渤滞。
然后調(diào)用每個(gè)watcher的`run`方法贬墩。
run () {
if (this.active) {
this.getAndInvoke(this.cb)
}
}
getAndInvoke (cb: Function) {
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
this.dirty = false
if (this.user) {
try {
cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, callback for watcher "${this.expression}"
)
}
} else {
cb.call(this.vm, value, oldValue)
}
}
}
`run`方法實(shí)際上就是調(diào)用了`getAndInvoke`方法。而`getAndInvoke`有調(diào)用了`this.get()`方法妄呕,`this.get()`方法中會(huì)調(diào)用`this.getter`陶舞,也就是`vm._update(vm._render(), hydrating)`去重新渲染更新組件。
## 總結(jié)
Vue的響應(yīng)式原理實(shí)際上就是利用了`Object.defineProperty`為對(duì)象的屬性定義了getter/setter绪励,用`Dep`和`Watcher`配合完成了依賴(lài)收集和派發(fā)更新的過(guò)程肿孵。每一個(gè)響應(yīng)式的屬性對(duì)應(yīng)一個(gè)Dep,而每一個(gè)組件對(duì)應(yīng)一個(gè)Watcher疏魏。當(dāng)屬性更新是就通知依賴(lài)這個(gè)屬性的組件去更新停做。