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

Vue中Keep-Alive緩存組件使用語法及原理深度解析

 更新時間:2024年07月09日 11:52:13   作者:前端菜鳥的自我修養(yǎng)  
keep-alive是vue中的內(nèi)置組件,能在組件切換過程中將狀態(tài)保留在內(nèi)存中,防止重復(fù)渲染DOM,這篇文章主要介紹了Vue中Keep-Alive緩存組件使用語法及原理,需要的朋友可以參考下

一、Keep-alive 是什么

keep-alive是vue中的內(nèi)置組件,能在組件切換過程中將狀態(tài)保留在內(nèi)存中,防止重復(fù)渲染DOM

keep-alive 包裹動態(tài)組件時,會緩存不活動的組件實例,而不是銷毀它們

keep-alive可以設(shè)置以下props屬性

  • include - 字符串或正則表達(dá)式。只有名稱匹配的組件會被緩存
  • exclude - 字符串或正則表達(dá)式。任何名稱匹配的組件都不會被緩存
  • max - 數(shù)字。最多可以緩存多少組件實例

關(guān)于keep-alive的基本用法:

<keep-alive>
  <component :is="view"></component>
</keep-alive>

使用includesexclude

<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
<!-- 正則表達(dá)式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
<!-- 數(shù)組 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive> 

匹配首先檢查組件自身的 name 選項,如果 name 選項不可用,則匹配它的局部注冊名稱 (父組件 components 選項的鍵值),匿名組件不能被匹配

設(shè)置了 keep-alive 緩存的組件,會多出兩個生命周期鉤子(activateddeactivated):

  • 首次進(jìn)入組件時:beforeRouteEnter > beforeCreate > created> mounted > activated > ... ... > beforeRouteLeave > deactivated
  • 再次進(jìn)入組件時:beforeRouteEnter >activated > ... ... > beforeRouteLeave > deactivated

二、使用場景

使用原則:當(dāng)我們在某些場景下不需要讓頁面重新加載時我們可以使用keepalive

舉個栗子:

當(dāng)我們從首頁–>列表頁–>商詳頁–>再返回,這時候列表頁應(yīng)該是需要keep-alive

從首頁–>列表頁–>商詳頁–>返回到列表頁(需要緩存)–>返回到首頁(需要緩存)–>再次進(jìn)入列表頁(不需要緩存),這時候可以按需來控制頁面的keep-alive

在路由中設(shè)置keepAlive屬性判斷是否需要緩存

{
  path: 'list',
  name: 'itemList', // 列表頁
  component (resolve) {
    require(['@/pages/item/list'], resolve)
 },
 meta: {
  keepAlive: true,
  title: '列表頁'
 }
}

使用<keep-alive>

<div id="app" class='wrapper'>
    <keep-alive>
        <!-- 需要緩存的視圖組件 --> 
        <router-view v-if="$route.meta.keepAlive"></router-view>
     </keep-alive>
      <!-- 不需要緩存的視圖組件 -->
     <router-view v-if="!$route.meta.keepAlive"></router-view>
</div>

三、原理分析

keep-alivevue中內(nèi)置的一個組件

源碼位置:src/core/components/keep-alive.js

export default {
  name: 'keep-alive',
  abstract: true,
  props: {
    include: [String, RegExp, Array],
    exclude: [String, RegExp, Array],
    max: [String, Number]
  },
  created () {
    this.cache = Object.create(null)
    this.keys = []
  },
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
  mounted () {
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },
  render() {
    /* 獲取默認(rèn)插槽中的第一個組件節(jié)點 */
    const slot = this.$slots.default
    const vnode = getFirstComponentChild(slot)
    /* 獲取該組件節(jié)點的componentOptions */
    const componentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      /* 獲取該組件節(jié)點的名稱,優(yōu)先獲取組件的name字段,如果name不存在則獲取組件的tag */
      const name = getComponentName(componentOptions)
      const { include, exclude } = this
      /* 如果name不在inlcude中或者存在于exlude中則表示不緩存,直接返回vnode */
      if (
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }
      const { cache, keys } = this
      /* 獲取組件的key值 */
      const key = vnode.key == null
        // 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
     /*  拿到key值后去this.cache對象中去尋找是否有該值,如果有則表示該組件有緩存,即命中緩存 */
      if (cache[key]) {
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest
        remove(keys, key)
        keys.push(key)
      }
        /* 如果沒有命中緩存,則將其設(shè)置進(jìn)緩存 */
        else {
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        /* 如果配置了max并且緩存的長度超過了this.max,則從緩存中刪除第一個 */
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }
      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}

可以看到該組件沒有template,而是用了render,在組件渲染的時候會自動執(zhí)行render函數(shù)

this.cache是一個對象,用來存儲需要緩存的組件,它將以如下形式存儲:

this.cache = {
    'key1':'組件1',
    'key2':'組件2',
    // ...
}

在組件銷毀的時候執(zhí)行pruneCacheEntry函數(shù)

function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const cached = cache[key]
  /* 判斷當(dāng)前沒有處于被渲染狀態(tài)的組件,將其銷毀*/
  if (cached && (!current || cached.tag !== current.tag)) {
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

mounted鉤子函數(shù)中觀測 include 和 exclude 的變化,如下:

mounted () {
    this.$watch('include', val => {
        pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
        pruneCache(this, name => !matches(val, name))
    })
}

如果include 或exclude 發(fā)生了變化,即表示定義需要緩存的組件的規(guī)則或者不需要緩存的組件的規(guī)則發(fā)生了變化,那么就執(zhí)行pruneCache函數(shù),函數(shù)如下:

function pruneCache (keepAliveInstance, filter) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const cachedNode = cache[key]
    if (cachedNode) {
      const name = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

在該函數(shù)內(nèi)對this.cache對象進(jìn)行遍歷,取出每一項的name值,用其與新的緩存規(guī)則進(jìn)行匹配,如果匹配不上,則表示在新的緩存規(guī)則下該組件已經(jīng)不需要被緩存,則調(diào)用pruneCacheEntry函數(shù)將其從this.cache對象剔除即可

關(guān)于keep-alive的最強大緩存功能是在render函數(shù)中實現(xiàn)

首先獲取組件的key值:

const key = vnode.key == null? 
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

拿到key值后去this.cache對象中去尋找是否有該值,如果有則表示該組件有緩存,即命中緩存,如下:

/* 如果命中緩存,則直接從緩存中拿 vnode 的組件實例 */
if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    /* 調(diào)整該組件key的順序,將其從原來的地方刪掉并重新放在最后一個 */
    remove(keys, key)
    keys.push(key)
} 

直接從緩存中拿 vnode 的組件實例,此時重新調(diào)整該組件key的順序,將其從原來的地方刪掉并重新放在this.keys中最后一個

this.cache對象中沒有該key值的情況,如下:

/* 如果沒有命中緩存,則將其設(shè)置進(jìn)緩存 */
else {
    cache[key] = vnode
    keys.push(key)
    /* 如果配置了max并且緩存的長度超過了this.max,則從緩存中刪除第一個 */
    if (this.max && keys.length > parseInt(this.max)) {
        pruneCacheEntry(cache, keys[0], keys, this._vnode)
    }
}

表明該組件還沒有被緩存過,則以該組件的key為鍵,組件vnode為值,將其存入this.cache中,并且把key存入this.keys

此時再判斷this.keys中緩存組件的數(shù)量是否超過了設(shè)置的最大緩存數(shù)量值this.max,如果超過了,則把第一個緩存組件刪掉

四、緩存后如何獲取數(shù)據(jù)

解決方案可以有以下兩種:

  • beforeRouteEnter

  • actived

actived

beforeRouteEnter

每次組件渲染的時候,都會執(zhí)行beforeRouteEnter

beforeRouteEnter(to, from, next){
    next(vm=>{
        console.log(vm)
        // 每次進(jìn)入路由執(zhí)行
        vm.getData()  // 獲取數(shù)據(jù)
    })
},

actived

keep-alive緩存的組件被激活的時候,都會執(zhí)行actived鉤子

activated(){
   this.getData() // 獲取數(shù)據(jù)
},

注意:服務(wù)器端渲染期間avtived不被調(diào)用

到此這篇關(guān)于Vue中Keep-Alive緩存組件使用語法及原理解析的文章就介紹到這了,更多相關(guān)vue Keep-Alive緩存組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • element-ui中使用upload組件獲取上傳文件信息

    element-ui中使用upload組件獲取上傳文件信息

    這篇文章主要介紹了element-ui中使用upload組件獲取上傳文件信息方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • vue中v-if?和v-permission?共同使用的坑及解決方案

    vue中v-if?和v-permission?共同使用的坑及解決方案

    這篇文章主要介紹了vue中v-if?和v-permission?共同使用的坑及解決方案的相關(guān)資料,需要的朋友可以參考下
    2023-07-07
  • Element實現(xiàn)表格分頁數(shù)據(jù)選擇+全選所有完善批量操作

    Element實現(xiàn)表格分頁數(shù)據(jù)選擇+全選所有完善批量操作

    這篇文章主要介紹了Element實現(xiàn)表格分頁數(shù)據(jù)選擇+全選所有完善批量操作,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • 使用Vue3和Echarts?5繪制帶有立體感流線中國地圖(推薦收藏!)

    使用Vue3和Echarts?5繪制帶有立體感流線中國地圖(推薦收藏!)

    最近接到一個需求是做一個中國地圖,下面這篇文章主要給大家介紹了關(guān)于如何使用Vue3和Echarts?5繪制帶有立體感流線中國地圖的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • vue3前端實現(xiàn)微信支付詳細(xì)步驟

    vue3前端實現(xiàn)微信支付詳細(xì)步驟

    這篇文章主要給大家介紹了vue3前端實現(xiàn)微信支付的詳細(xì)步驟,隨著移動端的普及和互聯(lián)網(wǎng)購買需求的增加,微信支付在電商領(lǐng)域中發(fā)揮著越來越重要的作用,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下
    2023-11-11
  • Vue內(nèi)存泄漏的識別和解決方案

    Vue內(nèi)存泄漏的識別和解決方案

    Vue是人氣爆棚且地表最強的JS(JavaScript)框架,祂允許我們構(gòu)建動態(tài)交互式的Web App,然但是,和任何軟件雷同,Vue App偶爾會遭遇內(nèi)存泄漏,導(dǎo)致性能暴跌和意外行為,今天,我們將深入Vue App內(nèi)存泄漏的原因,并探討識別和修復(fù)這些問題的錦囊妙計
    2023-11-11
  • 從0搭建vue3組件庫Input組件

    從0搭建vue3組件庫Input組件

    這篇文章主要介紹了從0搭建vue3組件庫Input組件,每個功能的實現(xiàn)代碼都做了精簡,方便大家快速定位到核心邏輯,接下來就開始對這些功能進(jìn)行實例代碼講解,需要的朋友可以參考下
    2022-11-11
  • element ui的el-input-number修改數(shù)值失效的問題及解決

    element ui的el-input-number修改數(shù)值失效的問題及解決

    這篇文章主要介紹了element ui的el-input-number修改數(shù)值失效的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 使用Vue完成一個簡單的todolist的方法

    使用Vue完成一個簡單的todolist的方法

    本篇文章主要介紹了使用Vue完成一個簡單的todolist的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • VUE 使用中踩過的坑

    VUE 使用中踩過的坑

    本篇是我對vue使用過程中以及對一些社區(qū)朋友提問我的問題中做的一些總結(jié),感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-02-02

最新評論

大姚县| 贵州省| 祁阳县| 观塘区| 桐庐县| 嘉善县| 池州市| 芦溪县| 庆元县| 虞城县| 东明县| 宿迁市| 平定县| 秀山| 横山县| 普洱| 攀枝花市| 普定县| 南丹县| 龙泉市| 崇礼县| 博客| 弥勒县| 祁阳县| 遂昌县| 天津市| 阜新| 四会市| 鄂托克前旗| 报价| 广水市| 静乐县| 永兴县| 循化| 贵港市| 枣强县| 桃源县| 葵青区| 方城县| 张掖市| 休宁县|