- <keep-alive> 不會在函數(shù)式組件中正常工作,因?yàn)樗鼈儧]有緩存實(shí)例。
- 結(jié)合router,緩存部分頁面
- activated 和 deactivate 生命周期鉤子
- include string或正則,只有名稱匹配的組件會被緩存 2.1.0+
- exclude string或正則, 名稱匹配的組件不會被緩存 2.1.0+
- max 最多可以緩存多少組件實(shí)例 2.5.0+
例子:
<keep-alive include="a,b" :include="['a','b']" :exclude="/a|b/" :max="10">
<component :is='view'></component>
</keep-alive>
下面開始講解應(yīng)用在保留列表當(dāng)前頁的案例中:
結(jié)合router,緩存部分頁面
- 布局router-view中
<template>
<div class="mainContainer-wrap">
<transition :name="name" mode="out-in" name="fade">
<keep-alive>
<router-view v-if="this.$route.meta.keepAlive"></router-view>
</keep-alive>
</transition>
<transition :name="name" mode="out-in" name="fade">
<router-view v-if="!this.$route.meta.keepAlive"></router-view>
</transition>
</div>
</template>
<script>
export default {
name: 'mainContainer',
data () {
return {
name: this.$route.name
}
},
mounted () {
// console.log(this.$route.meta.keepAlive)
}
}
</script>
- 在router/設(shè)置route的元信息 meta
{
path: '/dm',
component: Layout,
redirect: '/dm/basic',
name: '設(shè)備中心',
meta: {
title: '設(shè)備中心',
icon: ''
},
children: [{
path: 'basic',
name: 'Basic',
component: Basic,
meta: {
title: '設(shè)備管理',
keepAlive: true // 需要緩存
}
}, {
path: 'basic/decDetail',
name: 'DeviceDetail',
component: DeviceDetail,
meta: {
title: '設(shè)備詳情',
level: 2,
hidden: true,
keepAlive: false // 不需要緩存
}
}]
},
使用keep-alive會將數(shù)據(jù)保留在內(nèi)存中,如果每次進(jìn)入頁面的時(shí)候要獲取最新的數(shù)據(jù),需要 在 activated 生命周期中 重新獲取數(shù)據(jù),承擔(dān)原來created 鉤子中獲取數(shù)據(jù)的任務(wù)
設(shè)置了keep-alive的組件
第一次進(jìn)入: beforeRouteEnter => created => ... => activated => ... => deactivated
后續(xù)進(jìn)入:beforeRouteEnter => activated => deactivated,
只有第一次進(jìn)入該組件時(shí),才會走created鉤子,需要緩存的組件中activated時(shí)每次都會走的鉤子函數(shù)
- 列表頁鉤子函數(shù)設(shè)置
created () {
this.getList()
},
activated() {
//只刷新數(shù)據(jù),不改變整體的緩存
this.getList()
},
mounted () {
this.getProductName()
},
//修改列表頁的meta值,false時(shí)再次進(jìn)入頁面會重新請求數(shù)據(jù)。
beforeRouteLeave(to, from, next) {
from.meta.keepAlive = false
next()
},
- 詳情頁路由的鉤子函數(shù)設(shè)置
// 從詳情頁返回主頁時(shí)把主頁的keepAlive值設(shè)置為true(要做個(gè)判斷,判斷是不是返回到主頁的)
beforeRouteLeave (to, from, next) {
if (to.name === 'Basic') {
to.meta.keepAlive = true
} else {
to.meta.keepAlive = false
}
next()
},
效果如下:

826333-20191031183208111-74701893.gif
轉(zhuǎn)載自:https://www.cnblogs.com/mmzuo-798/p/11772950.html