vue2中computed原理

要理解這個(gè),首先要理解vue2的數(shù)據(jù)響應(yīng)式原理,因?yàn)閏omputed這個(gè)API的實(shí)現(xiàn)是建立在數(shù)據(jù)響應(yīng)式的基礎(chǔ)之上的。
這里附上vue響應(yīng)式原理的地址:vue2數(shù)據(jù)響應(yīng)式原理

在vue的watcher實(shí)例中配置了lazy,dirty,value屬性,就是用來(lái)配合實(shí)現(xiàn)computed的API。vue在初始化computed時(shí),會(huì)給每一個(gè)computed屬性配置一個(gè)watcher,并配置lazy的值為true。在new Watcher時(shí),還會(huì)設(shè)置dirty為true。由于lazy為true,這個(gè)時(shí)候并不會(huì)執(zhí)行computed配置的get方法,也就是說(shuō)不會(huì)去計(jì)算出這個(gè)計(jì)算屬性的值出來(lái),那么什么時(shí)候才計(jì)算呢?就是在執(zhí)行render函數(shù)時(shí),會(huì)去取計(jì)算屬性的值,這個(gè)時(shí)候,會(huì)執(zhí)行計(jì)算屬性的getter。在getter里面,會(huì)先判斷dirty的值(為true,則表示當(dāng)前計(jì)算屬性的值為臟值,已經(jīng)過(guò)期了,需要重新計(jì)算出來(lái);為false則表示當(dāng)前的值是最新的,不需要重新計(jì)算,直接取緩存里面的值就行了,也就是value字段的值)。如果為true,則調(diào)用watcher.evaluate方法計(jì)算最新的值出來(lái),然后將dirty設(shè)為false,把最新的值賦值給value。在計(jì)算最新的值時(shí),也就是執(zhí)行我們?cè)赾omputed對(duì)象中配置的相應(yīng)的get函數(shù)。根據(jù)之前講的響應(yīng)式原理,會(huì)先將當(dāng)前的watcher掛到dep的靜態(tài)屬性target上,然后執(zhí)行g(shù)et,在這個(gè)過(guò)程中,會(huì)使用到data中的屬性,然后進(jìn)行依賴(lài)收集,將computed的watcher存到data數(shù)據(jù)對(duì)應(yīng)的dep中去。完了之后,將watcher從targetStack中彈出,這是dep的靜態(tài)屬性target的值又變成了render函數(shù)的watcher。以上步驟執(zhí)行完后,會(huì)判斷當(dāng)前dep的target是否還有值,有的話(huà),會(huì)執(zhí)行watcher.depend()。這一步是為了讓依賴(lài)的data對(duì)應(yīng)的dep中不僅是收集到computed的wathcer,還要收集render函數(shù)的watcher,因?yàn)楫?dāng)我們依賴(lài)的data改變時(shí),不僅要通知到computed的watcher,還要通知render函數(shù)的watcher,達(dá)到重渲染的目的。然后會(huì)把最新的value值返回,這時(shí),render函數(shù)里面終于拿到了計(jì)算屬性的最新值了。假如后面繼續(xù)用到了這個(gè)計(jì)算屬性,那么在執(zhí)行計(jì)算屬性的getter時(shí),跟之前一樣,會(huì)先判斷dirty值,這個(gè)時(shí)候,dirty的值為false,則直接返回value值,也就是之前說(shuō)的取緩存的值,不會(huì)再次運(yùn)行一遍計(jì)算屬性的get函數(shù)了。
當(dāng)某個(gè)時(shí)候,計(jì)算屬性依賴(lài)的data數(shù)據(jù)變了,則會(huì)先后觸發(fā)computed的watcher,還有render函數(shù)的watcher。在將vue的數(shù)據(jù)響應(yīng)式原理時(shí),我們知道,數(shù)據(jù)改變時(shí),是會(huì)觸發(fā)watcher的update方法。在這個(gè)方法里面,首先判斷l(xiāng)azy是否為true,這就是針對(duì)計(jì)算屬性設(shè)計(jì)的。我們可以看看源碼片段:


vue2中watcher的update源碼片段.png

如果為true,則只做了一件非常簡(jiǎn)單的事,就是把dirty設(shè)為了true,然后就沒(méi)了。這個(gè)時(shí)候會(huì)去執(zhí)行render函數(shù)的watcher.update。也就是把render函數(shù)的執(zhí)行交給了nextTick去管理,這也是之前講過(guò)的。在執(zhí)行render函數(shù)時(shí),又使用到了這個(gè)計(jì)算屬性,那么,則會(huì)執(zhí)行這個(gè)計(jì)算屬性的getter,判斷dirty是否為true,由于剛剛在執(zhí)行computed的wathcer.update時(shí),把dirty設(shè)為了true,這個(gè)時(shí)候肯定會(huì)執(zhí)行watcher.evaluate重新去計(jì)算最新的值,也就是執(zhí)行我們配置在computed里面的get函數(shù)。接下來(lái)的其實(shí)跟前面所講的都是一樣的了。

這里附上關(guān)于computed初始化的源碼片段:

const computedWatcherOptions = { lazy: true }
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 // {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)) {
      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)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(`The computed property "${key}" is already defined as a method.`, vm)
      }
    }
  }
}

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
    }
  }
}

以上就是個(gè)人對(duì)于computed原理的理解了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容