1.基本用法
vue2.0提供了一個(gè)keep-alive組件用來(lái)緩存組件,避免多次加載相應(yīng)的組件,減少性能消耗
<keep-alive>
<component>
<!-- 組件將被緩存 -->
</component>
</keep-alive>
有時(shí)候 可能需要緩存整個(gè)站點(diǎn)的所有頁(yè)面,而頁(yè)面一般一進(jìn)去都要觸發(fā)請(qǐng)求的
在使用keep-alive的情況下
<keep-alive><router-view></router-view></keep-alive>
將首次觸發(fā)請(qǐng)求寫在created鉤子函數(shù)中,就能實(shí)現(xiàn)緩存,比如列表頁(yè),去了詳情頁(yè) 回來(lái),還是在原來(lái)的頁(yè)面
2.緩存部分頁(yè)面或者組件
(1)使用router.mate屬性
// 這是目前用的比較多的方式
<keep-alive>
<router-view v-if="!$route.meta.notKeepAlive"></router-view>
</keep-alive>
<router-view v-if="$route.meta.notKeepAlive"></router-view>
router設(shè)置
routes: [
{ path: '/', redirect: '/index', component: Index, mate: { keepAlive: true }},
{
path: '/common',
component: TestParent,
children: [
{ path: '/test2', component: Test2, mate: { keepAlive: true } }
]
}
// 表示index和test2都使用keep-alive
(2).使用新增屬性inlcude/exclude
2.1.0后提供了include/exclude兩個(gè)屬性 可以針對(duì)性緩存相應(yīng)的組件
<!-- comma-delimited string -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- regex (use v-bind) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
//其中a,b是組件的name
注意:這種方法都是預(yù)先知道組件的名稱的
(2)動(dòng)態(tài)判斷
<keep-alive :include="includedComponents">
<router-view></router-view>
</keep-alive>
includedComponents動(dòng)態(tài)設(shè)置即可