使用場(chǎng)景
講實(shí)現(xiàn)之前酌儒,我們先簡(jiǎn)單想一下一般會(huì)在哪些地方使用到computed付魔。一般我們比較常用的有一下幾種情景:
- 模版計(jì)算:在模版里某個(gè)或者通過一些處理诅病,比方說時(shí)間格式化等
- 動(dòng)態(tài)求值:數(shù)據(jù)依賴多個(gè)變量變化
以上這些場(chǎng)景我們實(shí)際上也可以通過method以及watch監(jiān)聽多個(gè)數(shù)據(jù)實(shí)現(xiàn)司澎。那么為什么需要computed物独,他有什么特性?
先貼一個(gè)官方的解釋:計(jì)算屬性是基于它們的響應(yīng)式依賴進(jìn)行緩存的备闲,只在相關(guān)響應(yīng)式依賴發(fā)生改變時(shí)它們才會(huì)重新求值晌端。
從這我們可以看到computed有兩個(gè)特性
- 值是響應(yīng)式變化(區(qū)別于method)
- 數(shù)據(jù)會(huì)進(jìn)行緩存
下面我們就從源碼角度分析一下,具體是怎么實(shí)現(xiàn)上面的兩個(gè)特性的恬砂。
入口
computed的源碼實(shí)現(xiàn)在目錄src/core/instance
咧纠,為了方便閱讀,代碼解析會(huì)省略部分代碼泻骤。
// 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)
}
}
vue在初始化的時(shí)候 會(huì)先去執(zhí)行```initProps, initMethods, initData 漆羔,然后進(jìn)行computed的初始化, 這里我們也就知道為什么在data初始化時(shí)狱掂,獲取不到computed的值
initState的時(shí)候判斷是不是有computed對(duì)象演痒,有的話執(zhí)行initComputed方法
initComputed
// state.js
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
const watchers = vm._computedWatchers = Object.create(null)
// 是否是服務(wù)端渲染
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
)
}
// 如果在data或者prop有相同的名稱存在的情況下,提示
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)
}
}
}
}
initComputed 做了幾件事情
生成一個(gè)空對(duì)象_computedWatchers趋惨,并掛載到vue實(shí)例上 (后續(xù)訪問key都是直接讀取這個(gè)對(duì)象)
獲取computed的getter嫡霞, 函數(shù)形式是函數(shù)本身,對(duì)象的話必須存在get函數(shù)
為computed對(duì)象的每一個(gè)key希柿,分配一個(gè)watch實(shí)例,并添加到_computedWatchers上
判斷养筒,確保不會(huì)出現(xiàn)于data曾撤、prop重名的字段,有重名提示晕粪,后續(xù)不執(zhí)行
執(zhí)行defineComputed:通過Object.defineProperty 設(shè)置代理挤悉,后續(xù)訪問
? 到這里大概我們可以猜測(cè)一下,computed的緩存應(yīng)該是通過生成一個(gè)對(duì)象巫湘,每個(gè)鍵值都綁定了一個(gè)watch實(shí)例用于依賴收集装悲。與其他地方使用watch不同的在于它傳入了配置參數(shù){ lazy: true }
, 這個(gè)的目的是讓實(shí)例化的時(shí)候不回立即求值,而是在訪問到它的地方才會(huì)去求值尚氛。
// src/core/observer/watcher.js
export default class Watch {
constructor () {
....
this.value = this.lazy
? undefined
: this.get()
}
}
defineComputed
既然初次實(shí)例化的時(shí)候并沒有求值诀诊,那么后續(xù)取值的時(shí)候是怎么去保證能拿到最新的數(shù)據(jù)呢?這個(gè)答案在defineComputed我們能找到阅嘶,接下去我們就分析一下這個(gè)方法属瓣,看一下怎么去實(shí)現(xiàn)求值與取值的载迄。
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)
}
defineComputed 通過 Object.defineProperty 為 computed的key值重新設(shè)置了get和set方法,對(duì)象情況下抡蛙,set就是computed的set函數(shù)护昧。通過cache判斷執(zhí)行的不同的get函數(shù)邏輯。
createComputedGetter
接下去看一下createComputedGetter 方法實(shí)現(xiàn)
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
}
}
}
? 這個(gè)方法里面才是computed能實(shí)現(xiàn)緩存的關(guān)鍵粗截。從這個(gè)函數(shù)我們可以看出基本邏輯和我們之前分析的一致惋耙,每次訪問key值時(shí),首先是從_computedWatchers 這個(gè)對(duì)象去取出對(duì)應(yīng)的watch實(shí)例熊昌, 返回wathc.value就是我們要的值绽榛。
? 這里還進(jìn)行了判斷了watch.dirty 也就是數(shù)據(jù)依賴變化的情況,執(zhí)行wathcer.evaluate() 重新獲取值
// src/core/observer/watcher.js
export default class Watch {
constructor () {
this.dirty = this.lazy
....
this.value = this.lazy
? undefined
: this.get()
}
}
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
}
evaluate () {
this.value = this.get()
this.dirty = false
}
update () {
/* istanbul ignore else */
if (this.lazy) {
// computed watch
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
? 初始化實(shí)例的時(shí)候dirty等于傳入的配置lazy 所以在第一次訪問計(jì)算屬性時(shí)浴捆,他會(huì)做一次求值蒜田,執(zhí)行g(shù)et更改value值。然后將dirty置為false选泻, 后續(xù)我們?cè)L問的時(shí)候就會(huì)直接返回這個(gè)值冲粤,并不會(huì)再次計(jì)算,這就是為什么computed的數(shù)據(jù)能緩存的關(guān)鍵所在页眯。
computed還有一個(gè)特性就是依賴的數(shù)據(jù)變化時(shí)梯捕,會(huì)跟隨變化。這塊涉及到依賴收集相關(guān)的窝撵,本篇不做展開傀顾。回憶一下之前的碌奉,在為key值分配watch的時(shí)候我們會(huì)把本身的get函數(shù)傳入watch實(shí)例短曾,然后在每次訪問key的時(shí)候,如果dirty為true就會(huì)執(zhí)行watch.get 方法赐劣,該方法執(zhí)行的就是我們傳入的computed的get函數(shù)嫉拐, 這個(gè)時(shí)候他內(nèi)部的響應(yīng)式依賴數(shù)據(jù)就會(huì)收集。后續(xù)依賴數(shù)據(jù)變化時(shí)就會(huì)執(zhí)行watch.update方法魁兼, 這個(gè)時(shí)候把就會(huì)再次把dirty設(shè)置為true婉徘, 接下去我們?cè)L問計(jì)算屬性就會(huì)再次執(zhí)行watch.get更新數(shù)據(jù)。
以上就是computed的完整實(shí)現(xiàn)
小結(jié):computed實(shí)現(xiàn)主要是在實(shí)例下的生成_computedWatchers對(duì)象咐汞,后續(xù)訪問都是直接訪問到這個(gè)對(duì)象盖呼。對(duì)象上的每個(gè)鍵值都是一個(gè)watch實(shí)例,訪問時(shí)返回watch的value值化撕, 通過dirty去控制是否重新計(jì)算几晤,每次依賴變化觸發(fā)watch的update方法,改變dirty的值植阴,下一次訪問的時(shí)候重新計(jì)算獲取值锌仅,否則直接返回上一次的值章钾。
以上就是個(gè)人對(duì)computed的實(shí)現(xiàn),如果有什么講的不對(duì)的热芹,歡迎評(píng)論回復(fù)指出贱傀。