在Vue實例初始化的過程中烟阐,initState
方法會調(diào)用initComputed
和initWatch
來分別初始化計算屬性和偵聽屬性,那么接下來就分析這兩個方法的實現(xiàn)拧晕。
計算屬性
這兩個方法都定義在core/instance/state.js
中
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (process.env.NODE_ENV !== 'production') {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
}
}
}
}
核心是首先是創(chuàng)建了vm._computedWatchers
屬性并設(shè)為一個空對象隙姿,然后對每個定義的計算屬性調(diào)用創(chuàng)建一個Watcher并調(diào)用defineComputed
方法:
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
const shouldCache = !isServerRendering()
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: userDef
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop
}
if (process.env.NODE_ENV !== 'production' &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
計算屬性的定義可以是一個函數(shù)或者一個對象。如果是一個函數(shù)厂捞,那么它將作為這個計算屬性的getter输玷。如果是一個對象,那么那么這個對象的get
屬性和set
屬性分別是這個計算屬性的getter和setter靡馁,同時可以設(shè)置cache=false
來禁止緩存欲鹏。
若果是需要緩存的情況,getter將被設(shè)為createComputedGetter
方法的返回值臭墨。
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
watcher.depend()
return watcher.evaluate()
}
}
}
計算屬性創(chuàng)建的Watcher與普通的Watcher的不同之處是赔嚎,在Watcher的構(gòu)造函數(shù)中有這么一段邏輯:
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
// ...
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
this.value = this.get()
}
}
在組件掛載時創(chuàng)建的Watcher尤误,this.value
是updateComponent
函數(shù),也就是創(chuàng)建Watcher的時候會立即做一次組件更新结缚。而計算屬性創(chuàng)建的Watcher沒有立即調(diào)用this.value
,而是創(chuàng)建了一個Dep
實例红竭。
當(dāng)組件渲染時訪問到計算屬性,就會調(diào)用它的getter茵宪。首先會拿到它對應(yīng)的watcher,執(zhí)行watcher.depend()
:
depend () {
if (this.dep && Dep.target) {
this.dep.depend()
}
}
此時Dep.target
是當(dāng)前正在渲染的組件的Watcher眉厨,也就是讓當(dāng)前的活動正在渲染的組件訂閱了這個計算屬性的變化。
然后調(diào)用了watcher.evaluate
:
evaluate () {
if (this.dirty) {
this.value = this.get()
this.dirty = false
}
return this.value
}
如果this.dirty
為true
那么就執(zhí)行this.get()
憾股,返回計算屬性的值。
this.get()
會調(diào)用pushTarget(this)
將Dep.target
設(shè)為自身服球,那么如果在執(zhí)行g(shù)etter的過程中依賴了其他的響應(yīng)式屬性茴恰,就會觸發(fā)它們的getter斩熊,這樣就會把它們的dep添加到當(dāng)前watcher中往枣,使當(dāng)前計算屬性的watcher訂閱以來的響應(yīng)式屬性的變化。
一旦計算屬性依賴的數(shù)據(jù)被修改,就會觸發(fā) setter分冈,執(zhí)行watcher.update()
方法通知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)
}
}
如果當(dāng)前計算屬性沒有被任何組件依賴,就僅僅把this.dirty
設(shè)置為true
雕沉。否則重新計算屬性值集乔,然后通知組件重新渲染。
偵聽屬性
偵聽屬性的初始化是在initWatch
方法中:
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
···
`initWatch`方法對每個偵聽屬性的回調(diào)函數(shù)執(zhí)行`createWatcher(vm, key, handler)`坡椒。如果一個偵聽屬性有多個回調(diào)函數(shù)可以使用一個數(shù)組扰路。handler還可以是一個包含options的Object
function createWatcher (
vm: Component,
expOrFn: string | Function,
handler: any,
options?: Object
) {
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
return vm.$watch(expOrFn, handler, options)
}
`createWatcehr`最終會調(diào)用`vm.$watch`方法。`vm.$watch`是Vue原型上的方法倔叼,它是在執(zhí)行`stateMixin`時添加到原型上的汗唱。
export function stateMixin (Vue: Class<Component>) {
// ...
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
}
通過`vm.$watch`方法創(chuàng)建的watcher是一個user watcher。用來觀察Vue實例上的一個響應(yīng)式屬性的變化丈攒,在變化時執(zhí)行回調(diào)函數(shù)哩罪。它可以有`immediate`或`deep`的選項。
user watcher的并沒有很大的區(qū)別肥印,只有邏輯上的不同识椰,這里就不分析了。