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

徹底揭秘keep-alive原理(小結)

 更新時間:2019年05月05日 14:22:30   作者:_安歌  
這篇文章主要介紹了徹底揭秘keep-alive原理(小結),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、前言

原文鏈接: https://github.com/qiudongwei/blog/issues/4

本文介紹的內(nèi)容包括:

  • keep-alive用法:動態(tài)組件&vue-router
  • keep-alive源碼解析
  • keep-alive組件及其包裹組件的鉤子
  • keep-alive組件及其包裹組件的渲染

二、keep-alive介紹與應用

2.1 keep-alive是什么

keep-alive是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出現(xiàn)在父組件鏈中;使用keep-alive包裹動態(tài)組件時,會緩存不活動的組件實例,而不是銷毀它們。

2.2 一個場景

用戶在某個列表頁面選擇篩選條件過濾出一份數(shù)據(jù)列表,由列表頁面進入數(shù)據(jù)詳情頁面,再返回該列表頁面,我們希望:列表頁面可以保留用戶的篩選(或選中)狀態(tài)。keep-alive就是用來解決這種場景。當然keep-alive不僅僅是能夠保存頁面/組件的狀態(tài)這么簡單,它還可以避免組件反復創(chuàng)建和渲染,有效提升系統(tǒng)性能。 總的來說,keep-alive用于保存組件的渲染狀態(tài)。

2.3 keep-alive用法 在動態(tài)組件中的應用

<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
 <component :is="currentComponent"></component>
</keep-alive>

在vue-router中的應用

<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
 <router-view></router-view>
</keep-alive>

include 定義緩存白名單,keep-alive會緩存命中的組件; exclude 定義緩存黑名單,被命中的組件將不會被緩存; max 定義緩存組件上限,超出上限使用LRU的策略置換緩存數(shù)據(jù)。

三、源碼剖析

keep-alive.js 內(nèi)部另外還定義了一些工具函數(shù),我們按住不表,先看它對外暴露的對象。

// src/core/components/keep-alive.js
export default {
 name: 'keep-alive',
 abstract: true, // 判斷當前組件虛擬dom是否渲染成真是dom的關鍵

 props: {
  include: patternTypes, // 緩存白名單
  exclude: patternTypes, // 緩存黑名單
  max: [String, Number] // 緩存的組件實例數(shù)量上限
 },

 created () {
  this.cache = Object.create(null) // 緩存虛擬dom
  this.keys = [] // 緩存的虛擬dom的健集合
 },

 destroyed () {
  for (const key in this.cache) { // 刪除所有的緩存
   pruneCacheEntry(this.cache, key, this.keys)
  }
 },

 mounted () {
  // 實時監(jiān)聽黑白名單的變動
  this.$watch('include', val => {
   pruneCache(this, name => matches(val, name))
  })
  this.$watch('exclude', val => {
   pruneCache(this, name => !matches(val, name))
  })
 },

 render () {
  // 先省略...
 }
}

可以看出,與我們定義組件的過程一樣,先是設置組件名為 keep-alive ,其次定義了一個 abstract 屬性,值為 true 。這個屬性在vue的官方教程并未提及,卻至關重要,后面的渲染過程會用到。 props 屬性定義了keep-alive組件支持的全部參數(shù)。

keep-alive在它生命周期內(nèi)定義了三個鉤子函數(shù):

created

初始化兩個對象分別緩存VNode(虛擬DOM)和VNode對應的健集合

destroyed

刪除 this.cache 中緩存的VNode實例。我們留意到,這里不是簡單地將 this.cache 至為 null ,而是遍歷調(diào)用 pruneCacheEntry 函數(shù)刪除。

// src/core/components/keep-alive.js
function pruneCacheEntry (
 cache: VNodeCache,
 key: string,
 keys: Array<string>,
 current?: VNode
) {
 const cached = cache[key]
 if (cached && (!current || cached.tag !== current.tag)) {
  cached.componentInstance.$destroy() // 執(zhí)行組件的destory鉤子函數(shù)
 }
 cache[key] = null
 remove(keys, key)
}

刪除緩存VNode還要對應執(zhí)行組件實例的 destory 鉤子函數(shù)

mounted

mounted 這個鉤子中對 includeexclude 參數(shù)進行監(jiān)聽,然后實時地更新(刪除) this.cache 對象數(shù)據(jù)。 pruneCache 函數(shù)的核心也是去調(diào)用 pruneCacheEntry 。

render

 // src/core/components/keep-alive.js
 render () {
  const slot = this.$slots.default
  const vnode: VNode = getFirstComponentChild(slot) // 找到第一個子組件對象
  const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
  if (componentOptions) { // 存在組件參數(shù)
   // check pattern
   const name: ?string = getComponentName(componentOptions) // 組件名
   const { include, exclude } = this
   if ( // 條件匹配
    // not included
    (include && (!name || !matches(include, name))) ||
    // excluded
    (exclude && name && matches(exclude, name))
   ) {
    return vnode
   }

   const { cache, keys } = this
   const key: ?string = vnode.key == null // 定義組件的緩存key
    // same constructor may get registered as different local components
    // so cid alone is not enough (#3269)
    ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
    : vnode.key
   if (cache[key]) { // 已經(jīng)緩存過該組件
    vnode.componentInstance = cache[key].componentInstance
    // make current key freshest
    remove(keys, key)
    keys.push(key) // 調(diào)整key排序
   } else {
    cache[key] = vnode // 緩存組件對象
    keys.push(key)
    // prune oldest entry
    if (this.max && keys.length > parseInt(this.max)) { // 超過緩存數(shù)限制,將第一個刪除
     pruneCacheEntry(cache, keys[0], keys, this._vnode)
    }
   }

   vnode.data.keepAlive = true // 渲染和執(zhí)行被包裹組件的鉤子函數(shù)需要用到
  }
  return vnode || (slot && slot[0])
 }

第一步:獲取keep-alive包裹著的第一個子組件對象及其組件名;

第二步:根據(jù)設定的黑白名單(如果有)進行條件匹配,決定是否緩存。不匹配,直接返回組件實例(VNode),否則執(zhí)行第三步;

第三步:根據(jù)組件ID和tag生成緩存Key,并在緩存對象中查找是否已緩存過該組件實例。如果存在,直接取出緩存值并更新該 keythis.keys 中的位置(更新key的位置是實現(xiàn)LRU置換策略的關鍵),否則執(zhí)行第四步;

第四步:在 this.cache 對象中存儲該組件實例并保存 key 值,之后檢查緩存的實例數(shù)量是否超過 max 的設置值,超過則根據(jù)LRU置換策略刪除最近最久未使用的實例(即是下標為0的那個key)。

第五步:最后并且很重要,將該組件實例的 keepAlive 屬性值設置為 true 。這個在 @ 不可忽視:鉤子函數(shù) 章節(jié)會再次出場。

四、重頭戲:渲染

4.1 Vue的渲染過程

借一張圖看下Vue渲染的整個過程:

 

Vue的渲染是從圖中的 render 階段開始的,但keep-alive的渲染是在patch階段,這是構建組件樹(虛擬DOM樹),并將VNode轉換成真正DOM節(jié)點的過程。

簡單描述從 renderpatch 的過程

我們從最簡單的 new Vue 開始:

import App from './App.vue'

new Vue({
 render: h => h(App),
}).$mount('#app')
  • Vue在渲染的時候先調(diào)用原型上的 _render 函數(shù)將組件對象轉化為一個VNode實例;而 _render 是通過調(diào)用 createElementcreateEmptyVNode 兩個函數(shù)進行轉化;
  • createElement 的轉化過程會根據(jù)不同的情形選擇 new VNode 或者調(diào)用 createComponent 函數(shù)做VNode實例化;
  • 完成VNode實例化后,這時候Vue調(diào)用原型上的 _update 函數(shù)把VNode渲染為真實DOM,這個過程又是通過調(diào)用 __patch__ 函數(shù)完成的(這就是pacth階段了)

用一張圖表達:

 

4.2 keep-alive組件的渲染

我們用過keep-alive都知道,它不會生成真正的DOM節(jié)點,這是怎么做到的?

// src/core/instance/lifecycle.js
export function initLifecycle (vm: Component) {
 const options = vm.$options
 // 找到第一個非abstract的父組件實例
 let parent = options.parent
 if (parent && !options.abstract) {
  while (parent.$options.abstract && parent.$parent) {
   parent = parent.$parent
  }
  parent.$children.push(vm)
 }
 vm.$parent = parent
 // ...
}

Vue在初始化生命周期的時候,為組件實例建立父子關系會根據(jù) abstract 屬性決定是否忽略某個組件。在keep-alive中,設置了 abstract: true ,那Vue就會跳過該組件實例。

keep-alive包裹的組件是如何使用緩存的?

patch 階段,會執(zhí)行 createComponent 函數(shù):

// src/core/vdom/patch.js
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
  let i = vnode.data
  if (isDef(i)) {
   const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
   if (isDef(i = i.hook) && isDef(i = i.init)) {
    i(vnode, false /* hydrating */)
   }

   if (isDef(vnode.componentInstance)) {
    initComponent(vnode, insertedVnodeQueue)
    insert(parentElm, vnode.elm, refElm) // 將緩存的DOM(vnode.elm)插入父元素中
    if (isTrue(isReactivated)) {
     reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)
    }
    return true
   }
  }
 }

在首次加載被包裹組件時,由 keep-alive.js 中的 render 函數(shù)可知, vnode.componentInstance 的值是 undefined , keepAlive 的值是 true ,因為keep-alive組件作為父組件,它的 render 函數(shù)會先于被包裹組件執(zhí)行;那么就只執(zhí)行到 i(vnode, false /* hydrating */) ,后面的邏輯不再執(zhí)行;

再次訪問被包裹組件時, vnode.componentInstance 的值就是已經(jīng)緩存的組件實例,那么會執(zhí)行 insert(parentElm, vnode.elm, refElm) 邏輯,這樣就直接把上一次的DOM插入到了父元素中。

五、不可忽視:鉤子函數(shù)

 5.1 只執(zhí)行一次的鉤子

一般的組件,每一次加載都會有完整的生命周期,即生命周期里面對應的鉤子函數(shù)都會被觸發(fā),為什么被keep-alive包裹的組件卻不是呢? 我們在 @ 源碼剖析 章節(jié)分析到,被緩存的組件實例會為其設置 keepAlive = true ,而在初始化組件鉤子函數(shù)中:

// src/core/vdom/create-component.js
const componentVNodeHooks = {
 init (vnode: VNodeWithData, hydrating: boolean): ?boolean {
  if (
   vnode.componentInstance &&
   !vnode.componentInstance._isDestroyed &&
   vnode.data.keepAlive
  ) {
   // kept-alive components, treat as a patch
   const mountedNode: any = vnode // work around flow
   componentVNodeHooks.prepatch(mountedNode, mountedNode)
  } else {
   const child = vnode.componentInstance = createComponentInstanceForVnode(
    vnode,
    activeInstance
   )
   child.$mount(hydrating ? vnode.elm : undefined, hydrating)
  }
 }
 // ...
}

可以看出,當 vnode.componentInstancekeepAlive 同時為truly值時,不再進入 $mount 過程,那 mounted 之前的所有鉤子函數(shù)( beforeCreate 、 created 、 mounted )都不再執(zhí)行。

5.2 可重復的activated

patch 的階段,最后會執(zhí)行 invokeInsertHook 函數(shù),而這個函數(shù)就是去調(diào)用組件實例(VNode)自身的 insert 鉤子:

// src/core/vdom/patch.js
 function invokeInsertHook (vnode, queue, initial) {
  if (isTrue(initial) && isDef(vnode.parent)) {
   vnode.parent.data.pendingInsert = queue
  } else {
   for (let i = 0; i < queue.length; ++i) {
    queue[i].data.hook.insert(queue[i]) // 調(diào)用VNode自身的insert鉤子函數(shù)
   }
  }
 }

再看 insert 鉤子:

// src/core/vdom/create-component.js
const componentVNodeHooks = {
 // init()
 insert (vnode: MountedComponentVNode) {
  const { context, componentInstance } = vnode
  if (!componentInstance._isMounted) {
   componentInstance._isMounted = true
   callHook(componentInstance, 'mounted')
  }
  if (vnode.data.keepAlive) {
   if (context._isMounted) {
    queueActivatedComponent(componentInstance)
   } else {
    activateChildComponent(componentInstance, true /* direct */)
   }
  }
 // ...
}

在這個鉤子里面,調(diào)用了 activateChildComponent 函數(shù)遞歸地去執(zhí)行所有子組件的 activated 鉤子函數(shù):

// src/core/instance/lifecycle.js
export function activateChildComponent (vm: Component, direct?: boolean) {
 if (direct) {
  vm._directInactive = false
  if (isInInactiveTree(vm)) {
   return
  }
 } else if (vm._directInactive) {
  return
 }
 if (vm._inactive || vm._inactive === null) {
  vm._inactive = false
  for (let i = 0; i < vm.$children.length; i++) {
   activateChildComponent(vm.$children[i])
  }
  callHook(vm, 'activated')
 }
}

相反地, deactivated 鉤子函數(shù)也是一樣的原理,在組件實例(VNode)的 destroy 鉤子函數(shù)中調(diào)用 deactivateChildComponent 函數(shù)。

參考

 Vue技術揭秘|keep-alive

Vue源碼

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關文章

  • vuejs指令詳解

    vuejs指令詳解

    本文介紹了vuejs指令的相關知識,具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • Vue正則表達式限制input的輸入范圍

    Vue正則表達式限制input的輸入范圍

    我們有時需要限制文本框輸入內(nèi)容的類型,本節(jié)分享下正則表達式限制文本框只能輸入數(shù)字、小數(shù)點、英文字母、漢字等代碼,感興趣的朋友跟隨小編一起看看吧
    2023-12-12
  • Vue 組件參數(shù)校驗與非props特性的方法

    Vue 組件參數(shù)校驗與非props特性的方法

    這篇文章主要介紹了Vue 組件參數(shù)校驗與非props特性的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • 簡易vuex4核心原理及實現(xiàn)源碼分析

    簡易vuex4核心原理及實現(xiàn)源碼分析

    這篇文章主要為大家介紹了簡易vuex4核心原理及實現(xiàn)源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • vue中錨點的三種方法

    vue中錨點的三種方法

    本文給大家?guī)砹藇ue中錨點的三種方法,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧
    2018-07-07
  • vue實現(xiàn)頁面打印自動分頁的兩種方法

    vue實現(xiàn)頁面打印自動分頁的兩種方法

    這篇文章主要為大家詳細介紹了vue實現(xiàn)頁面打印自動分頁的兩種方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • vue?如何引入本地某個文件?require

    vue?如何引入本地某個文件?require

    這篇文章主要介紹了vue?如何引入本地某個文件?require,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • vue項目base64字符串轉圖片的實現(xiàn)代碼

    vue項目base64字符串轉圖片的實現(xiàn)代碼

    這篇文章主要介紹了vue項目base64字符串轉圖片的實現(xiàn)代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • vue實現(xiàn)拖拽小圖標

    vue實現(xiàn)拖拽小圖標

    這篇文章主要為大家詳細介紹了vue實現(xiàn)拖拽小圖標,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • vue實現(xiàn)學生信息管理系統(tǒng)

    vue實現(xiàn)學生信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了vue實現(xiàn)學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-05-05

最新評論

太康县| 肃宁县| 承德市| 澄迈县| 如皋市| 平湖市| 宝清县| 庄河市| 黄大仙区| 凌源市| 昌吉市| 仁寿县| 婺源县| 桦南县| 库尔勒市| 大关县| 龙岩市| 木里| 师宗县| 章丘市| 佛学| 南溪县| 方山县| 高州市| 陈巴尔虎旗| 天峻县| 昌乐县| 习水县| 延吉市| 天水市| 萝北县| 佛山市| 林周县| 介休市| 宁德市| 英山县| 天水市| 高碑店市| 邻水| 元氏县| 晋城|