keep-alive
有時候我們不希望組件被重新渲染影響使用體驗;或者處於性能考慮,避免多次重復渲染降低性能。而是希望組件可以緩存下來,維持當前的狀態。這時候就可以用到keep-alive組件。
官網解釋:
包裹動態組件時,會緩存不活動的組件實例,而不是銷毀它們。和 相似, 是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出現在父組件鏈中。 當組件在 內被切換,它的 activated 和 deactivated 這兩個生命周期鈎子函數將會被對應執行。 在 2.2.0 及其更高版本中,activated 和 deactivated 將會在 樹內的所有嵌套組件中觸發。 主要用於保留組件狀態或避免重新渲染
應用場景
如果未使用keep-alive組件,則在頁面回退時仍然會重新渲染頁面,觸發created鈎子,使用體驗不好。 在以下場景中使用keep-alive組件會顯著提高用戶體驗,菜單存在多級關系,多見於列表頁+詳情頁的場景如:
- 商品列表頁點擊商品跳轉到商品詳情,返回后仍顯示原有信息
- 訂單列表跳轉到訂單詳情,返回,等等場景。
生命周期
被包含在 keep-alive 中創建的組件,會多出兩個生命周期的鈎子: activated
與 deactivated
activated
- 在 keep-alive 組件激活時調用
- 該鈎子函數在服務器端渲染期間不被調用
deactivated
- 在 keep-alive 組件停用時調用
- 該鈎子在服務器端渲染期間不被調用
使用 keep-alive 會將數據保留在內存中,如果要在每次進入頁面的時候獲取最新的數據,需要在 activated 階段獲取數據,承擔原來 created 鈎子函數中獲取數據的任務。
注意: 只有組件被 keep-alive 包裹時,這兩個生命周期函數才會被調用,如果作為正常組件使用,是不會被調用的,以及在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive 中,這兩個鈎子函數依然不會被調用!另外,在服務端渲染時,此鈎子函數也不會被調用。
- 初次進入時:created > mounted > activated;退出后觸發 deactivated
- 再次進入:會觸發 activated;事件掛載的方法等,只執行一次的放在 mounted 中;組件每次進去執行的方法放在 activated 中
props屬性
- include - 字符串或正則表達式。只有名稱匹配的組件會被緩存
- exclude - 字符串或正則表達式。任何名稱匹配的組件都不會被緩存。
- max - 數字。最多可以緩存多少組件實例。
項目實踐
緩存所有頁面
在 App.vue 里面
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
根據條件緩存頁面
在 App.vue 里面
<template>
<div id="app">
// 1. 將緩存 name 為 test 的組件
<keep-alive include='test'>
<router-view/>
</keep-alive>
// 2. 將緩存 name 為 a 或者 b 的組件,結合動態組件使用
<keep-alive include='a,b'>
<router-view/>
</keep-alive>
// 3. 使用正則表達式,需使用 v-bind
<keep-alive :include='/a|b/'>
<router-view/>
</keep-alive>
// 5.動態判斷
<keep-alive :include='includedComponents'>
<router-view/>
</keep-alive>
// 5. 將不緩存 name 為 test 的組件
<keep-alive exclude='test'>
<router-view/>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
結合Router,緩存部分頁面
1、在 router 目錄下的 index.js 文件里
import Vue from 'vue'
import Router from 'vue-router'
const Home = resolve => require(['@/components/home/home'], resolve)
const Goods = resolve => require(['@/components/home/goods'], resolve)
const Ratings = resolve => require(['@/components/home/ratings'], resolve)
const Seller = resolve => require(['@/components/home/seller'], resolve)
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home,
redirect: 'goods',
children: [
{
path: 'goods',
name: 'goods',
component: Goods,
meta: {
keepAlive: false // 不需要緩存
}
},
{
path: 'ratings',
name: 'ratings',
component: Ratings,
meta: {
keepAlive: true // 需要緩存
}
},
{
path: 'seller',
name: 'seller',
component: Seller,
meta: {
keepAlive: true // 需要緩存
}
}
]
}
]
})
2、在 App.vue 里面
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>