摘要:本文通過官方文件結合原始碼來分析computed/method/watch的區別。
Tips:本文分析的原始碼版本是v2.6.11,文章中牽涉到vue響應式系統原理部分,如果不是很瞭解,建議先閱讀上一篇文章《深入解析vue響應式原理》。
computed
首先來看官網的解釋:計算屬性是基於響應式依賴進行快取的,只在相關響應式依賴發生改變時它們才會重新求值。
下面通過原始碼來分析computed是怎麼實現響應式快取的:
initComputed
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)
}
}
}
}
- 首先建立一個computedWatchers掛到vm上;
- 遍歷computed屬性,依次將單個computed屬性的get方法作為引數建立Watcher例項儲存到computedWatchers中;
- 再將單個computed屬性作為引數傳入defineComputed方法。
defineComputed
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
const shouldCache = !isServerRendering()
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef)
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop
sharedPropertyDefinition.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)
}
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter () {
return fn.call(this, this)
}
}
將計算屬性掛到vm上,定義getter屬性方法,方法會執行計算屬性獲取新值(新值會儲存到Watcher.value中)及收集依賴該computed屬性的檢視。
總結:
- 頁面初始渲染時,讀取computed屬性值,computed屬性值的getter函式讀取data資料,觸發data的getter方法,將computed屬性對應的Watcher繫結到data的依賴收集器Dep中;
- computed屬性getter方法中,還會呼叫Watcher.depend方法,將上層檢視的觀察者也新增到data的依賴收集器Dep中;
- data屬性值變更後,將會呼叫Dep.notify方法,通知所有依賴的Watcher進行update方法;
- 首先觸發computed關聯Watcher的update方法,由於lazy為true,將會設定dirty為true,表示computed屬性依賴的data值已經變更,但不會呼叫Watcher的get方法獲取新值。
- 然後觸發檢視關聯Watcher的update方法,在更新頁面時會呼叫computed屬性值,觸發定義的getter函式。由於當前dirty為true,會執行關聯Watcher.get方法獲取新值,更新Watcher.value的值,並返回新值,完成頁面的重新渲染。
method
function initMethods (vm: Component, methods: Object) {
const props = vm.$options.props
for (const key in methods) {
if (process.env.NODE_ENV !== 'production') {
if (typeof methods[key] !== 'function') {
warn(
`Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
`Did you reference the function correctly?`,
vm
)
}
if (props && hasOwn(props, key)) {
warn(
`Method "${key}" has already been defined as a prop.`,
vm
)
}
if ((key in vm) && isReserved(key)) {
warn(
`Method "${key}" conflicts with an existing Vue instance method. ` +
`Avoid defining component methods that start with _ or $.`
)
}
}
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
method的原始碼很簡單,只是繫結了所有method的this為vm。
watch
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)
}
}
}
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)
}
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) {
try {
cb.call(vm, watcher.value)
} catch (error) {
handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
}
}
return function unwatchFn () {
watcher.teardown()
}
}
Tips:Watcher物件原始碼在上文中《深入解析vue響應式原理》分析過,這裡就不再贅述。
經過分析watch的原始碼可以發現,實際上每一個watch屬性對應生成了一個Watcher物件,通過獲取data屬性值將Watcher新增到依賴收集器Dep中,當data資料更新時,就會呼叫Dep.notify通知Watcher。
總結:
- computed屬性是根據依賴的data屬性(有可能多個)進行更新標記,等檢視獲取該computed屬性資料時才執行更新計算,並將值快取到對應的Watcher例項中。且只有當data資料變化後,檢視讀取關聯computed屬性才會重新計算結果。
- method屬性是根據檢視需要即時計算獲得,不具有快取性質,當關聯data資料沒有更新時也會重新計算。
- watch屬性是有且只能依賴單個data屬性,當data資料變化後,會立即觸發Watcher.update,呼叫對應watch定義的方法執行。不具有快取性質。