本文聊聊另外一種watcher:computedWatcher
的實現。express
<template>
<div class="container">
<div>{{fullname}}</div>
</div>
</template>
<script>
import child from './components/child'
export default {
name: 'App',
data(vm) {
return {
firstname: 'klay',
lastname: 'thompson'
}
},
computed: {
fullname() {
return this.firstname + this.lastname
}
},
}
複製代碼
這裏定義一個fullname的計算屬性,根據firstname
和lastname
的值計算值,當這兩個值發生變化時fullname會從新計算bash
// core/instance/state.js
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
...
if (opts.computed) initComputed(vm, opts.computed)
...
}
複製代碼
// 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)
}
}
}
}
複製代碼
vm._computedWatchers
,這裏的computedWatcherOptions = { lazy: true }
// core/instance/state.js
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
}
...
Object.defineProperty(target, key, sharedPropertyDefinition)
}
複製代碼
這裏typeof userDef === 'function'
且不是服務端渲染,因此會走sharedPropertyDefinition.get = createComputedGetter(key)
,sharedPropertyDefinition
就是一個公用的propertyDescriptor
函數
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
複製代碼
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
}
}
}
複製代碼
當getter觸發時,根據key拿到對應的watcher,判斷watcher依賴的值是否有更新,有則計算值,最後返回watcher的value。oop
// core/observer/watcher.js
/** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */
evaluate () {
this.value = this.get()
this.dirty = false
}
複製代碼
evaluate方法專門爲computedWatcher服務的ui
// // core/observer/watcher.js
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
}
複製代碼
這裏的this.getter
就是前面的userDef
,進行求值時會觸發依賴項的依賴收集,之前面的例子來看,firstname
和lastname
會將fullname
對應的watcher收集。當這兩個值中任意一個發生變化時就會觸發watcher的從新計算。this
Vue經過在Vm實例上定義getter,在getter裏面計算watcher的值,那麼確定有Vm.fullname
這樣的取值語句觸發getter,這是在哪一個地方觸發的呢?lua
render
函數,在mount過程當中會執行render函數,裏面有vm.fullname
的求值。this.fullname
也是同樣。// core/observer/watcher.js
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
複製代碼
computedWatcher的update方法並不會將當前watcher添加進queue
,只是將watcher的dirty標記爲true,在nextTick時render函數再次執行,再看一遍前面的getter取值spa
//core/instance/state.js
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
}
}
}
複製代碼
官網中也有描述,computed的功能用method也能夠實現,好比咱們改寫前面的例子prototype
<template>
<div class="container">
<div>{{fullname()}}</div>
</div>
</template>
<script>
import child from './components/child'
export default {
name: 'App',
data(vm) {
return {
firstname: 'klay',
lastname: 'thompson'
}
},
methods: {
fullname() {
return this.firstname + this.lastname
}
},
}
複製代碼
method雖然實現了功能,可是這裏有個問題,不管fristname
和lastname
是否變化,求值函數都會執行一遍,假設這個取值過程十分複雜,在依賴的值沒有變化時從新計算是沒有必要的,這種狀況下采用computed
更合理,watcher.dirty === false
,不會從新計算3d