成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

徹底揭秘keep-alive原理

lavnFan / 3400人閱讀

摘要:我們留意到,這里不是簡單地將置為,而是遍歷調(diào)用函數(shù)刪除。執(zhí)行組件的鉤子函數(shù)刪除緩存還要對應(yīng)執(zhí)行組件實(shí)例的鉤子函數(shù)。這個(gè)在不可忽視鉤子函數(shù)章節(jié)會再次出場。參考技術(shù)揭秘源碼

一、前言

原文鏈接:github.com/qi...

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

keep-alive用法:動(dòng)態(tài)組件&vue-router

keep-alive源碼解析

keep-alive組件及其包裹組件的鉤子

keep-alive組件及其包裹組件的渲染

二、keep-alive介紹與應(yīng)用 2.1 keep-alive是什么

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

2.2 一個(gè)場景

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

2.3 keep-alive用法

在動(dòng)態(tài)組件中的應(yīng)用

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

在vue-router中的應(yīng)用

<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, // 判斷當(dāng)前組件虛擬dom是否渲染成真是dom的關(guān)鍵

  props: {
    include: patternTypes, // 緩存白名單
    exclude: patternTypes, // 緩存黑名單
    max: [String, Number] // 緩存的組件實(shí)例數(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 () {
    // 實(shí)時(shí)監(jiān)聽黑白名單的變動(dòng)
    this.$watch("include", val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch("exclude", val => {
      pruneCache(this, name => !matches(val, name))
    })
  },

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

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

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

created

初始化兩個(gè)對象分別緩存VNode(虛擬DOM)和VNode對應(yīng)的鍵集合

destroyed

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

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

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

mounted

mounted這個(gè)鉤子中對includeexclude參數(shù)進(jìn)行監(jiān)聽,然后實(shí)時(shí)地更新(刪除)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) // 找到第一個(gè)子組件對象
    const componentOptions: ");if (componentOptions) { // 存在組件參數(shù)
      // check pattern
      const name: ");// 組件名
      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: ");null // 定義組件的緩存key
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ");`::${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ù)限制,將第一個(gè)刪除
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

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

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

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

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

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

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

四、重頭戲:渲染 4.1 Vue的渲染過程

借一張圖看下Vue渲染的整個(gè)過程:

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

簡單描述從renderpatch的過程

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

import App from "./App.vue"

new Vue({
  render: h => h(App),
}).$mount("#app")

Vue在渲染的時(shí)候先調(diào)用原型上的_render函數(shù)將組件對象轉(zhuǎn)化為一個(gè)VNode實(shí)例;而_render是通過調(diào)用createElementcreateEmptyVNode兩個(gè)函數(shù)進(jìn)行轉(zhuǎn)化;

createElement的轉(zhuǎn)化過程會根據(jù)不同的情形選擇new VNode或者調(diào)用createComponent函數(shù)做VNode實(shí)例化;

完成VNode實(shí)例化后,這時(shí)候Vue調(diào)用原型上的_update函數(shù)把VNode渲染為真實(shí)DOM,這個(gè)過程又是通過調(diào)用__patch__函數(shù)完成的(這就是pacth階段了)

用一張圖表達(dá):

4.2 keep-alive組件的渲染

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

// src/core/instance/lifecycle.js
export function initLifecycle (vm: Component) {
  const options = vm.$options
  // 找到第一個(gè)非abstract的父組件實(shí)例
  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在初始化生命周期的時(shí)候,為組件實(shí)例建立父子關(guān)系會根據(jù)abstract屬性決定是否忽略某個(gè)組件。在keep-alive中,設(shè)置了abstract: true,那Vue就會跳過該組件實(shí)例。

最后構(gòu)建的組件樹中就不會包含keep-alive組件,那么由組件樹渲染成的DOM樹自然也不會有keep-alive相關(guān)的節(jié)點(diǎn)了。

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

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

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

五、不可忽視:鉤子函數(shù) 5.1 只執(zhí)行一次的鉤子

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

// src/core/vdom/create-component.js
const componentVNodeHooks = {
  init (vnode: VNodeWithData, hydrating: 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 ");undefined, hydrating)
    }
  }
  // ...
}

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

5.2 可重復(fù)的activated

patch的階段,最后會執(zhí)行invokeInsertHook函數(shù),而這個(gè)函數(shù)就是去調(diào)用組件實(shí)例(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 */)
      }
    }
  // ...
}

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

// src/core/instance/lifecycle.js
export function activateChildComponent (vm: Component, direct");) {
  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ù)也是一樣的原理,在組件實(shí)例(VNode)的destroy鉤子函數(shù)中調(diào)用deactivateChildComponent函數(shù)。

參考

Vue技術(shù)揭秘|keep-alive

Vue源碼

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/7314.html

相關(guān)文章

  • 徹底隱藏Nginx版本號的安全性與方法

    摘要:默認(rèn)是顯示版本號的,如這樣就給人家看到你的服務(wù)器版本是,前些時(shí)間暴出了一些版本漏洞,就是說有些版本有漏洞,而有些版本沒有。這樣暴露出來的版本號就容易變成攻擊者可利用的信息。 Nginx默認(rèn)是顯示版本號的,如: [root@hadooptest ~]# curl -I www.nginx.org HTTP/1.1 200 OK Server: nginx/0.8.44 Date: Tu...

    starsfun 評論0 收藏0
  • 徹底隱藏Nginx版本號的安全性與方法

    摘要:默認(rèn)是顯示版本號的,如這樣就給人家看到你的服務(wù)器版本是,前些時(shí)間暴出了一些版本漏洞,就是說有些版本有漏洞,而有些版本沒有。這樣暴露出來的版本號就容易變成攻擊者可利用的信息。 Nginx默認(rèn)是顯示版本號的,如: [root@hadooptest ~]# curl -I www.nginx.org HTTP/1.1 200 OK Server: nginx/0.8.44 Date: Tu...

    GHOST_349178 評論0 收藏0
  • 詳解Vue.js 技術(shù)

    本文主要從8個(gè)章節(jié)詳解vue技術(shù)揭秘,小編覺得挺有用的,分享給大家。 為了把 Vue.js 的源碼講明白,課程設(shè)計(jì)成由淺入深,分為核心、編譯、擴(kuò)展、生態(tài)四個(gè)方面去講,并拆成了八個(gè)章節(jié),如下: 準(zhǔn)備工作 Introduction 認(rèn)識 Flow Vue.js 源碼目錄設(shè)計(jì) Vue.js 源碼構(gòu)建 從入口開始 數(shù)據(jù)驅(qū)動(dòng) Introduction new Vue 發(fā)生了什么 Vue ...

    saucxs 評論0 收藏0

發(fā)表評論

0條評論

最新活動(dòng)
閱讀需要支付1元查看
<