最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue之Computed依賴收集與更新原理分析

 更新時間:2023年11月16日 10:38:07   作者:蘭亭古墨  
這篇文章主要介紹了Vue之Computed依賴收集與更新原理分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

Computed依賴收集與更新原理

今天面了家小公司,上來直接問 computed 底層原理,面試官是這樣問的,data 中定義了 a 和 b 變量。

computed 里面定義了 c 屬性,c 的結(jié)果依賴與 a 和 b,模板中使用了變量 c。

假設(shè)改變了 a,請問底層是如何收集依賴,如何觸發(fā)更新的?

<div>{{ c }}</div>
data(){
	return {
		a: 'foo',
		b: 'bar'
	}
},
computed: {
	c() { 
		return this.a + ' - ' + this.b;
	 }
},
mounted(){
	setTimeout(() => { this.a = 'FOO' }, 1000)
}

頁面效果:先顯示了 foo - bar,一秒之后顯示 FOO - bar

這里查源碼后,對computed原理簡述

如下:

1、initState 函數(shù)中初始化了 initComputed

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

2、initComputed 函數(shù)中遍歷 computed 中每一個屬性,并且 new Watcher(computed watcher),可以看到傳入 Watcher 構(gòu)造函數(shù)的 cb 是 noop,它是一個空函數(shù)。

并且 defineComputed

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

defineComputed 中使用了 Object.defineProperty 對屬性進行劫持,獲取是返回對應(yīng)的 getter 即 createComputedGetter

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

看到這里,我們大致可以理解,Vue 組件在初始化時,initState -> initComputed -> new Watcher() 計算watcher,傳入的 callback 是 computer 屬性的 getter,由于 computed 是 lazy: true watcher,所以 new Watcher 時并不會立即執(zhí)行 watcher 實例上的 get(), 而是在 defineComputed 函數(shù)里面調(diào)用 createComputedGetter 函數(shù),在 createComputedGetter 函數(shù)執(zhí)行了 watcher.evaluate() 進而執(zhí)行了 watcher.get().

執(zhí)行 watcher.get() 首先 pushTarget(this),將 Dep.target 賦值為當前的 computed watcher,然后執(zhí)行 this.getter

也就是執(zhí)行 computer 屬性配置的 getter,執(zhí)行g(shù)etter 就會訪問所依賴的每一個值,就會被 Object.defineProperty 劫持到進入 get ,執(zhí)行 dep.depend() , 會為每一個屬性對應(yīng)的 dep 實例添加一個 computed watcher,同時這個 computed watcher 也會保存對應(yīng)的 dep。

說了這么多都在講 computed watcher,那修改 this.a 頁面為什么會發(fā)生更新呢?

答案:因為 this.a 的依賴中不僅有 computed watcher 還有一個 render watcher

原因:

$mount 是會執(zhí)行 mountComponent,會創(chuàng)建一個 render watcher,它會立即執(zhí)行 cb(目前 Dep.target 是 render watcher),調(diào)用 render 函數(shù)在底層編譯模板,最后訪問屬性計算屬性 c,訪問計算屬性 c 就必定會訪問 a,當訪問 a 時會觸發(fā) defineComputed 中的 Object.defineProperty 進而劫持調(diào)用 createComputedGetter,進而調(diào)用 watcher.depend(),這個 watcher 是 computed watcher

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
    }
  }
}
// Watcher.js
depend () {
  let i = this.deps.length
  while (i--) {
    this.deps[i].depend()
  }
}

調(diào)用 watcher.depend() , this 指的是 computed watcher,會將 computed watcher 里面的 deps 保存在所有依賴調(diào)用 deps[i].depend(),進而調(diào)用 Dep 類中的 Dep.target.addDep(this),使得 render watcher 中保存了當前的 dep,dep 中同時保存了 render watcher。

dep 中同時保存了 render watcher。就可以看出,示例中的屬性 a 的 dep 中也會保存 render watcher,所以 a 屬性的 dep 中有兩個 watcher: [computedWatcher, renderWatcher]

所以,修改 a 屬性的值,最后 notify 會清空這個 保存 watcher 的隊列,進行頁面更新!Okay!

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • vue中provide和inject的用法及說明(vue組件爺孫傳值)

    vue中provide和inject的用法及說明(vue組件爺孫傳值)

    這篇文章主要介紹了vue中provide和inject的用法及說明(vue組件爺孫傳值),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • vue3中的createApp分析

    vue3中的createApp分析

    這篇文章主要介紹了vue3中的createApp分析,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • 前端vue-cli項目中使用img圖片和background背景圖的幾種方法

    前端vue-cli項目中使用img圖片和background背景圖的幾種方法

    這篇文章主要介紹了前端vue-cli項目中使用img圖片和background背景圖的幾種方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • 前端vue-cropperjs實現(xiàn)圖片裁剪方案

    前端vue-cropperjs實現(xiàn)圖片裁剪方案

    這篇文章主要為大家介紹了前端vue-cropperjs實現(xiàn)圖片裁剪方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • vue數(shù)據(jù)雙向綁定的注意點

    vue數(shù)據(jù)雙向綁定的注意點

    這篇文章主要為大家詳細介紹了vue數(shù)據(jù)雙向綁定的注意點,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Vue2.0生命周期的理解

    Vue2.0生命周期的理解

    這篇文章主要為大家介紹了Vue2.0生命周期,思考與理解“el被新創(chuàng)建的vm.$el替換”這句話,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • 詳解如何配置vue-cli3.0的vue.config.js

    詳解如何配置vue-cli3.0的vue.config.js

    這篇文章主要介紹了詳解如何配置vue-cli3.0的vue.config.js,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Vue+ElementUI怎么處理超大表單實例講解

    Vue+ElementUI怎么處理超大表單實例講解

    在本篇文章里小編給大家整理的是一篇關(guān)于Vue+ElementUI怎么處理超大表單實例講解內(nèi)容,以后需要的朋友可以跟著學(xué)習(xí)參考下。
    2021-11-11
  • vue+elementUI動態(tài)增加表單項并添加驗證的代碼詳解

    vue+elementUI動態(tài)增加表單項并添加驗證的代碼詳解

    這篇文章主要介紹了vue+elementUI動態(tài)增加表單項并添加驗證的代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • Vue3使用element-plus組件不顯示問題

    Vue3使用element-plus組件不顯示問題

    這篇文章主要介紹了Vue3使用element-plus組件不顯示問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03

最新評論

咸阳市| 察隅县| 尚义县| 鲁山县| 东平县| 逊克县| 和林格尔县| 抚松县| 陕西省| 抚顺县| 聂荣县| 双鸭山市| 河东区| 沈阳市| 昌宁县| 泌阳县| 拜城县| 祁连县| 瓮安县| 新闻| 洪湖市| 界首市| 敦化市| 台江县| 信丰县| 海盐县| 林州市| 西乌珠穆沁旗| 北海市| 泾川县| 长丰县| 庄河市| 喜德县| 比如县| 饶河县| 太湖县| 霍林郭勒市| 来凤县| 金秀| 阿城市| 泽库县|