vue2.0 keep-alive最佳實(shí)踐

1.基本用法

vue2.0提供了一個(gè)keep-alive組件用來緩存組件,避免多次加載相應(yīng)的組件,減少性能消耗

<keep-alive>
<component>
  <!-- 組件將被緩存 -->
</component>
</keep-alive>

有時(shí)候 可能需要緩存整個(gè)站點(diǎn)的所有頁面,而頁面一般一進(jìn)去都要觸發(fā)請求的
在使用keep-alive的情況下

<keep-alive><router-view></router-view></keep-alive>

將首次觸發(fā)請求寫在created鉤子函數(shù)中,就能實(shí)現(xiàn)緩存,比如列表頁,去了詳情頁 回來,還是在原來的頁面

2.緩存部分頁面或者組件

(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è)屬性 可以針對性緩存相應(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è)置即可

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,563評(píng)論 19 139
  • keep-alive用法 <keep-alive> 包裹動(dòng)態(tài)組件時(shí),會(huì)緩存不活動(dòng)的組件實(shí)例,而不是銷毀它們。和 ...
    MrLhx閱讀 1,592評(píng)論 0 2
  • vue 2.0 漸進(jìn)式框架 MVC 單向通信 > m:model 數(shù)據(jù)層 保存數(shù)據(jù) > v:view視圖層 用戶界...
    web前端ling閱讀 864評(píng)論 0 0
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,177評(píng)論 0 29
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,040評(píng)論 25 709

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