vue.js 使用keep-alive設(shè)置返回不刷新

一、在首頁(yè)點(diǎn)擊一條數(shù)據(jù)進(jìn)入詳情頁(yè),按返回鍵返回首頁(yè)時(shí)頁(yè)面刷新了重新調(diào)用接口,用戶體驗(yàn)比較差,不流暢,這里整理總結(jié)一下我的解決方案。。。

<keep-alive>是Vue的內(nèi)置組件,能在組件切換過程中將狀態(tài)保留在內(nèi)存中,防止重復(fù)渲染DOM。vue2.0提供了一個(gè)keep-alive組件用來緩存組件,避免多次加載相應(yīng)的組件,減少性能消耗。

二、它有兩個(gè)生命周期:

  • activated: keep-alive組件激活時(shí)調(diào)用
  • deactivated: keep-alive組件停用時(shí)調(diào)用
    它提供了include與exclude兩個(gè)屬性,允許組件有條件地進(jìn)行緩存。

三、實(shí)現(xiàn)原理

  • 首先,你要知道Vue.js內(nèi)部將DOM節(jié)點(diǎn)抽象成了一個(gè)個(gè)的VNode節(jié)點(diǎn),這個(gè)我之前寫過相關(guān)文章可以參考VNode節(jié)點(diǎn)。所以,keep-alive的緩存也是基于VNode節(jié)點(diǎn)的而不是直接存儲(chǔ)DOM結(jié)構(gòu)。
  • 其實(shí)就是將需要緩存的VNode節(jié)點(diǎn)保存在this.cache中/在render時(shí),如果VNode的name符合在緩存條件(可以用include以及exclude控制),則會(huì)從this.cache中取出之前緩存的VNode實(shí)例進(jìn)行渲染。
    keep-alive是Vue.js的一個(gè)內(nèi)置組件。它能夠不活動(dòng)的組件實(shí)例保存在內(nèi)存中,而不是直接將其銷毀,它是一個(gè)抽象組件,不會(huì)被渲染到真實(shí)DOM中,也不會(huì)出現(xiàn)在父組件鏈中。

它提供了include與exclude兩個(gè)屬性,允許組件有條件地進(jìn)行緩存。

具體內(nèi)容可以參考官網(wǎng)

使用

用法

<keep-alive>
    <component></component>
</keep-alive></pre>

這里的component組件會(huì)被緩存起來。

舉個(gè)栗子

<keep-alive>
    <coma v-if="test"></coma>
    <comb v-else="test"></comb>
</keep-alive>
<button @click="test=handleClick">請(qǐng)點(diǎn)擊</button>
export default {
    data () {
        return {
            test: true
        }
    },
    methods: {
        handleClick () {
            this.test = !this.test;
        }
    }
}

在點(diǎn)擊button時(shí)候,coma與comb兩個(gè)組件會(huì)發(fā)生切換,但是這時(shí)候這兩個(gè)組件的狀態(tài)會(huì)被緩存起來,比如說coma與comb組件中都有一個(gè)input標(biāo)簽,那么input標(biāo)簽中的內(nèi)容不會(huì)因?yàn)榻M件的切換而消失。

props

keep-alive組件提供了include與exclude兩個(gè)屬性來允許組件有條件地進(jìn)行緩存,二者都可以用逗號(hào)分隔字符串、正則表達(dá)式或一個(gè)數(shù)組來表示。

<keep-alive include="a">
  <component></component>
</keep-alive>

將緩存name為a的組件。

<keep-alive exclude="a">
  <component></component>
</keep-alive>

name為a的組件將不會(huì)被緩存。

生命鉤子

keep-alive提供了兩個(gè)生命鉤子,分別是activated與deactivated。

因?yàn)閗eep-alive會(huì)將組件保存在內(nèi)存中,并不會(huì)銷毀以及重新創(chuàng)建,所以不會(huì)重新調(diào)用組件的created等方法,需要用activated與deactivated這兩個(gè)生命鉤子來得知當(dāng)前組件是否處于活動(dòng)狀態(tài)。


深入keep-alive組件實(shí)現(xiàn)

說完了keep-alive組件的使用,我們從源碼角度看一下keep-alive組件究竟是如何實(shí)現(xiàn)組件的緩存的呢?

created與destroyed鉤子

created鉤子會(huì)創(chuàng)建一個(gè)cache對(duì)象,用來作為緩存容器,保存vnode節(jié)點(diǎn)。

created () {
    /* 緩存對(duì)象 */
    this.cache = Object.create(null)
},

destroyed鉤子則在組件被銷毀的時(shí)候清除cache緩存中的所有組件實(shí)例。

/* destroyed鉤子中銷毀所有cache中的組件實(shí)例 */
destroyed () {
    for (const key in this.cache) {
        pruneCacheEntry(this.cache[key])
    }
},

render

接下來是render函數(shù)。

render () {
    /* 得到slot插槽中的第一個(gè)組件 */
    const vnode: VNode = getFirstComponentChild(this.$slots.default)

    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
        // check pattern
        /* 獲取組件名稱,優(yōu)先獲取組件的name字段,否則是組件的tag */
        const name: ?string = getComponentName(componentOptions)
        /* name不在inlcude中或者在exlude中則直接返回vnode(沒有取緩存) */
        if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
        )) {
            return vnode
        }
        const key: ?string = 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
        /* 如果已經(jīng)做過緩存了則直接從緩存中獲取組件實(shí)例給vnode,還未緩存過則進(jìn)行緩存 */
        if (this.cache[key]) {
            vnode.componentInstance = this.cache[key].componentInstance
        } else {
            this.cache[key] = vnode
        }
        /* keepAlive標(biāo)記位 */
        vnode.data.keepAlive = true
    }
    return vnode
}

首先通過getFirstComponentChild獲取第一個(gè)子組件,獲取該組件的name(存在組件名則直接使用組件名,否則會(huì)使用tag)。接下來會(huì)將這個(gè)name通過include與exclude屬性進(jìn)行匹配,匹配不成功(說明不需要進(jìn)行緩存)則不進(jìn)行任何操作直接返回vnode,vnode是一個(gè)VNode類型的對(duì)象,不了解VNode的同學(xué)可以參考筆者的另一篇文章[《VNode節(jié)點(diǎn)》

/* 檢測(cè)name是否匹配 */
function matches (pattern: string | RegExp, name: string): boolean {
  if (typeof pattern === 'string') {
    /* 字符串情況,如a,b,c */
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
    /* 正則 */
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}

檢測(cè)include與exclude屬性匹配的函數(shù)很簡(jiǎn)單,include與exclude屬性支持字符串如"a,b,c"這樣組件名以逗號(hào)隔開的情況以及正則表達(dá)式。matches通過這兩種方式分別檢測(cè)是否匹配當(dāng)前組件。

if (this.cache[key]) {
    vnode.componentInstance = this.cache[key].componentInstance
} else {
    this.cache[key] = vnode
}

接下來的事情很簡(jiǎn)單,根據(jù)key在this.cache中查找,如果存在則說明之前已經(jīng)緩存過了,直接將緩存的vnode的componentInstance(組件實(shí)例)覆蓋到目前的vnode上面。否則將vnode存儲(chǔ)在cache中。

最后返回vnode(有緩存時(shí)該vnode的componentInstance已經(jīng)被替換成緩存中的了)。

watch

用watch來監(jiān)聽pruneCache與pruneCache這兩個(gè)屬性的改變,在改變的時(shí)候修改cache緩存中的緩存數(shù)據(jù)。

watch: {
    /* 監(jiān)視include以及exclude,在被修改的時(shí)候?qū)ache進(jìn)行修正 */
    include (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => matches(val, name))
    },
    exclude (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => !matches(val, name))
    }
},

來看一下pruneCache的實(shí)現(xiàn)。

/* 修正cache */
function pruneCache (cache: VNodeCache, current: VNode, filter: Function) {
  for (const key in cache) {
    /* 取出cache中的vnode */
    const cachedNode: ?VNode = cache[key]
    if (cachedNode) {
      const name: ?string = getComponentName(cachedNode.componentOptions)
      /* name不符合filter條件的,同時(shí)不是目前渲染的vnode時(shí),銷毀vnode對(duì)應(yīng)的組件實(shí)例(Vue實(shí)例),并從cache中移除 */
      if (name && !filter(name)) {
        if (cachedNode !== current) {
          pruneCacheEntry(cachedNode)
        }
        cache[key] = null
      }
    }
  }
} 

/* 銷毀vnode對(duì)應(yīng)的組件實(shí)例(Vue實(shí)例) */
function pruneCacheEntry (vnode: ?VNode) {
  if (vnode) {
    vnode.componentInstance.$destroy()
  }
}

遍歷cache中的所有項(xiàng),如果不符合filter指定的規(guī)則的話,則會(huì)執(zhí)行pruneCacheEntry。pruneCacheEntry則會(huì)調(diào)用組件實(shí)例的$destroy方法來將組件銷毀。

最后

Vue.js內(nèi)部將DOM節(jié)點(diǎn)抽象成了一個(gè)個(gè)的VNode節(jié)點(diǎn),keep-alive組件的緩存也是基于VNode節(jié)點(diǎn)的而不是直接存儲(chǔ)DOM結(jié)構(gòu)。它將滿足條件(pruneCache與pruneCache)的組件在cache對(duì)象中緩存起來,在需要重新渲染的時(shí)候再將vnode節(jié)點(diǎn)從cache對(duì)象中取出并渲染。

?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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