手摸手帶你理解Vue的Computed原理


前言

computed 在 vue 中是很常用的屬性配置,它能夠隨着依賴屬性的變化而變化,為我們帶來很大便利。那么本文就來帶大家全面理解 computed 的內部原理以及工作流程。

在這之前,希望你能夠對響應式原理有一些理解,因為 computed 是基於響應式原理進行工作。如果你對響應式原理還不是很了解,可以閱讀我的上一篇文章:手摸手帶你理解Vue響應式原理

 

computed 用法

想要理解原理,最基本就是要知道如何使用,這對於后面的理解有一定的幫助。

第一種,函數聲明:

Copy
var vm = new vue({ el: '#example', data: { message: 'Hello' }, computed: { // 計算屬性的 getter reversedMessage: function () { // `this` 指向 vm 實例 return this.message.split('').reverse().join('') } } }) 

第二種,對象聲明:

Copy
computed: {
  fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } 
溫馨提示:computed 內使用的 data 屬性,下文統稱為“依賴屬性”
 

工作流程

先來了解下 computed 的大概流程,看看計算屬性的核心點是什么。

入口文件:

Copy
// 源碼位置:/src/core/instance/index.js import { initMixin } from './init' import { stateMixin } from './state' import { renderMixin } from './render' import { eventsMixin } from './events' import { lifecycleMixin } from './lifecycle' import { warn } from '../util/index' function Vue (options) { this._init(options) } initMixin(Vue) stateMixin(Vue) eventsMixin(Vue) lifecycleMixin(Vue) renderMixin(Vue) export default Vue 

_init:

Copy
// 源碼位置:/src/core/instance/init.js export function initMixin (Vue: Class<Component>) { Vue.prototype._init = function (options?: Object) { const vm: Component = this // a uid vm._uid = uid++ // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options) } else { // mergeOptions 對 mixin 選項和傳入的 options 選項進行合並 // 這里的 $options 可以理解為 new Vue 時傳入的對象 vm.$options = mergeOptions( resolveconstructorOptions(vm.constructor), options || {}, vm ) } // expose real self vm._self = vm initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate') initInjections(vm) // resolve injections before data/props // 初始化數據 initState(vm) initProvide(vm) // resolve provide after data/props callHook(vm, 'created') if (vm.$options.el) { vm.$mount(vm.$options.el) } } } 

initState:

Copy
// 源碼位置:/src/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 */) } // 這里會初始化 Computed if (opts.computed) initComputed(vm, opts.computed) if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch) } } 

initComputed:

Copy
// 源碼位置:/src/core/instance/state.js function initComputed (vm: Component, computed: Object) { // $flow-disable-line // 1 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] // 2 const getter = typeof userDef === 'function' ? userDef : userDef.get if (!isSSR) { // create internal watcher for the computed property. // 3 watchers[key] = new Watcher( vm, getter || noop, noop, { lazy: true } ) } // 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)) { // 4 defineComputed(vm, key, userDef) } } } 
  1. 實例上定義 _computedWatchers 對象,用於存儲“計算屬性Watcher”
  2. 獲取計算屬性的 getter,需要判斷是函數聲明還是對象聲明
  3. 創建“計算屬性Watcher”,getter 作為參數傳入,它會在依賴屬性更新時進行調用,並對計算屬性重新取值。需要注意 Watcher 的 lazy 配置,這是實現緩存的標識
  4. defineComputed 對計算屬性進行數據劫持

defineComputed:

Copy
// 源碼位置:/src/core/instance/state.js const noop = function() {} // 1 const sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop } export function defineComputed ( target: any, key: string, userDef: Object | Function ) { // 判斷是否為服務端渲染 const shouldCache = !isServerRendering() if (typeof userDef === 'function') { // 2 sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : createGetterInvoker(userDef) sharedPropertyDefinition.set = noop } else { // 3 sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : createGetterInvoker(userDef.get) : noop sharedPropertyDefinition.set = userDef.set || noop } // 4 Object.defineProperty(target, key, sharedPropertyDefinition) } 
  1. sharedPropertyDefinition 是計算屬性初始的屬性描述對象
  2. 計算屬性使用函數聲明時,設置屬性描述對象的 get 和 set
  3. 計算屬性使用對象聲明時,設置屬性描述對象的 get 和 set
  4. 對計算屬性進行數據劫持,sharedPropertyDefinition 作為第三個給參數傳入

客戶端渲染使用 createComputedGetter 創建 get,服務端渲染使用 createGetterInvoker 創建 get。它們兩者有很大的不同,服務端渲染不會對計算屬性緩存,而是直接求值:

Copy
function createGetterInvoker(fn) {
  return function computedGetter () { return fn.call(this, this) } } 

但我們平常更多的是討論客戶端渲染,下面看看 createComputedGetter 的實現。

createComputedGetter:

Copy
// 源碼位置:/src/core/instance/state.js function createComputedGetter (key) { return function computedGetter () { // 1 const watcher = this._computedWatchers && this._computedWatchers[key] if (watcher) { // 2 if (watcher.dirty) { watcher.evaluate() } // 3 if (Dep.target) { watcher.depend() } // 4 return watcher.value } } } 

這里就是計算屬性的實現核心,computedGetter 也就是計算屬性進行數據劫持時觸發的 get。

  1. 在上面的 initComputed 函數中,“計算屬性Watcher”就存儲在實例的_computedWatchers上,這里取出對應的“計算屬性Watcher”
  2. watcher.dirty 是實現計算屬性緩存的觸發點,watcher.evaluate 對計算屬性重新求值
  3. 依賴屬性收集“渲染Watcher”
  4. 計算屬性求值后會將值存儲在 value 中,get 返回計算屬性的值
 

計算屬性緩存及更新

緩存

下面我們來將 createComputedGetter 拆分,分析它們單獨的工作流程。這是緩存的觸發點:

Copy
if (watcher.dirty) {
  watcher.evaluate()
}

接下來看看 Watcher 相關實現:

Copy
export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; lazy: boolean; sync: boolean; dirty: boolean; active: boolean; deps: Array<Dep>; newDeps: Array<Dep>; depIds: SimpleSet; newDepIds: SimpleSet; before: ?Function; getter: Function; value: any; constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options if (options) { this.deep = !!options.deep this.user = !!options.user this.lazy = !!options.lazy this.sync = !!options.sync this.before = options.before } else { this.deep = this.user = this.lazy = this.sync = false } this.cb = cb this.id = ++uid // uid for batching this.active = true // dirty 初始值等同於 lazy this.dirty = this.lazy // for lazy watchers this.deps = [] this.newDeps = [] this.depIds = new Set() this.newDepIds = new Set() // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn } this.value = this.lazy ? undefined : this.get() } } 

還記得創建“計算屬性Watcher”,配置的 lazy 為 true。dirty 的初始值等同於 lazy。所以在初始化頁面渲染,對計算屬性取值時,會執行一次 watcher.evaluate。

Copy
evaluate() {
  this.value = this.get() this.dirty = false } 

求值后將值賦給 this.value,上面 createComputedGetter 內的 watcher.value 就是在這里更新。接着 dirty 置為 false,如果依賴屬性沒有變化,下一次取值時,是不會執行 watcher.evaluate 的, 而是直接就返回 watcher.value,這樣就實現了緩存機制。

更新

依賴屬性在更新時,會調用 dep.notify:

Copy
notify() {
  this.subs.forEach(watcher => watcher.update()) } 

然后執行 watcher.update:

Copy
update() {
  if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) } } 

由於“計算屬性Watcher”的 lazy 為 true,這里 dirty 會置為 true。等到頁面渲染對計算屬性取值時,執行 watcher.evaluate 重新求值,計算屬性隨之更新。

 

依賴屬性收集依賴

收集計算屬性Watcher

初始化時,頁面渲染會將“渲染Watcher”入棧,並掛載到Dep.target

在頁面渲染過程中遇到計算屬性,因此執行 watcher.evaluate 的邏輯,內部調用 this.get:

Copy
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 { popTarget() this.cleanupDeps() } return value } 
Copy
Dep.target = null let stack = [] // 存儲 watcher 的棧 export function pushTarget(watcher) { stack.push(watcher) Dep.target = watcher } export function popTarget(){ stack.pop() Dep.target = stack[stack.length - 1] } 

pushTarget 輪到“計算屬性Watcher”入棧,並掛載到Dep.target,此時棧中為 [渲染Watcher, 計算屬性Watcher]

this.getter 對計算屬性求值,在獲取依賴屬性時,觸發依賴屬性的 數據劫持get,執行 dep.depend 收集依賴(“計算屬性Watcher”)

收集渲染Watcher

this.getter 求值完成后popTragte,“計算屬性Watcher”出棧,Dep.target 設置為“渲染Watcher”,此時的 Dep.target 是“渲染Watcher”

Copy
if (Dep.target) {
  watcher.depend()
}

watcher.depend 收集依賴:

Copy
depend() {
  let i = this.deps.length while (i--) { this.deps[i].depend() } } 

deps 內存儲的是依賴屬性的 dep,這一步是依賴屬性收集依賴(“渲染Watcher”)

經過上面兩次收集依賴后,依賴屬性的 subs 存儲兩個 Watcher,[計算屬性Watcher,渲染Watcher]

為什么依賴屬性要收集渲染Watcher

我在初次閱讀源碼時,很奇怪的是依賴屬性收集到“計算屬性Watcher”不就好了嗎?為什么依賴屬性還要收集“渲染Watcher”?

第一種場景:模板里同時用到依賴屬性和計算屬性

Copy
<template>
  <div>{{msg}} {{msg1}}</div>
</template>

export default { data(){ return { msg: 'hello' } }, computed:{ msg1(){ return this.msg + ' world' } } } 

模板有用到依賴屬性,在頁面渲染對依賴屬性取值時,依賴屬性就存儲了“渲染Watcher”,所以 watcher.depend 這步是屬於重復收集的,但 watcher 內部會去重。

這也是我為什么會產生疑問的點,Vue 作為一個優秀的框架,這么做肯定有它的道理。於是我想到了另一個場景能合理解釋 watcher.depend 的作用。

第二種場景:模板內只用到計算屬性

Copy
<template>
  <div>{{msg1}}</div>
</template>

export default { data(){ return { msg: 'hello' } }, computed:{ msg1(){ return this.msg + ' world' } } } 

模板上沒有使用到依賴屬性,頁面渲染時,那么依賴屬性是不會收集 “渲染Watcher”的。此時依賴屬性里只會有“計算屬性Watcher”,當依賴屬性被修改,只會觸發“計算屬性Watcher”的 update。而計算屬性的 update 里僅僅是將 dirty 設置為 true,並沒有立刻求值,那么計算屬性也不會被更新。

所以需要收集“渲染Watcher”,在執行完“計算屬性Watcher”后,再執行“渲染Watcher”。頁面渲染對計算屬性取值,執行 watcher.evaluate 才會重新計算求值,頁面計算屬性更新。

秒收目錄站https://www.tomove.com.cn

總結

計算屬性原理和響應式原理都是大同小異的,同樣的是使用數據劫持以及依賴收集,不同的是計算屬性有做緩存優化,只有在依賴屬性變化時才會重新求值,其它情況都是直接返回緩存值。服務端不對計算屬性緩存。

計算屬性更新的前提需要“渲染Watcher”的配合,因此依賴屬性的 subs 中至少會存儲兩個 Watcher。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM