Vue 頁面緩存keep-alive

  1. keep-alive的基礎使用

最基礎的通常是結合動態組件去使用:vue

<keep-alive>
    <component :is="currentView"></component>
</keep-alive>
new Vue({
    el: '#app',
    data(){
        return {
            currentView: Test //Test爲引入的子組件
        }
    }
})
複製代碼
  1. 生命週期鉤子

被包含在 中建立的組件,會多出兩個生命週期的鉤子: activated 與 deactivated正則表達式

activated 在組件被激活時調用,在組件第一次渲染時也會被調用,以後每次keep-alive激活時被調用。數組

deactivated 在組件被停用時調用。緩存

注意:只有組件被 keep-alive 包裹時,這兩個生命週期纔會被調用,若是做爲正常組件使用,是不會被調用,以及在 2.1.0 版本以後,使用 exclude 排除以後,就算被包裹在 keep-alive 中,這兩個鉤子依然不會被調用!另外在服務端渲染時此鉤子也不會被調用的。bash

  1. 配合router-view使用

有些時候可能須要將整個路由頁面一切緩存下來,也就是將 進行緩存。這種使用場景仍是蠻多的。app

在vue 2.1.0 以前,大部分是這樣實現的:ui

<keep-alive>
    <router-view v-if="$router.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$router.meta.keepAlive"></router-view>
複製代碼
//router配置
new Router({
    routes: [
        {
            name: 'a',
            path: '/a',
            component: A,
            meta: {
                keepAlive: true
            }
        },
        {
            name: 'b',
            path: '/b',
            component: B
        }
    ]
})
複製代碼

這樣配置路由的路由元信息以後,a路由的 $router.meta.keepAlive 便爲 true ,而b路由則爲 false 。 因此爲 true 的將被包裹在 keep-alive 中,爲 false 的則在外層。這樣a路由便達到了被緩存的效果,若是還有想要緩存的路由,只須要在路由元中加入 keepAlive: true 便可。spa

  1. 在2.1.0版本以後

在vue 2.1.0 版本以後,keep-alive 新加入了兩個屬性: include(包含的組件緩存生效) 與 exclude(排除的組件不緩存,優先級大於include) 。code

include 和 exclude 屬性容許組件有條件地緩存。兩者均可以用逗號分隔字符串、正則表達式或一個數組來表示。 當使用正則或者是數組時,必定要使用 v-bind !component

<!-- 逗號分隔字符串,只有組件a與b被緩存。這樣使用場景變得更有意義了 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
<!-- 正則表達式 (須要使用 v-bind,符合匹配規則的都會被緩存) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
<!-- Array (須要使用 v-bind,被包含的都會被緩存) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>
複製代碼
相關文章
相關標籤/搜索