vue 中 keepAlive


項目開發中在用戶由分類頁category進入detail需保存用戶狀態,查閱了Vue官網后,發現vue2.0提供了一個keep-alive組件。

keep-alive的介紹如下:
1, 把切換出去的組件保留在內存中,可以保留它的狀態或避免重新渲染
2、<keep-alive>是抽象組件,它自身不會渲染DOM元素,也不會出現在父組件鏈中。
3、當組件在 <keep-alive> 內被切換,它的  activated 和  deactivated 這兩個生命周期鈎子函數將會被對應執行。
注:在 2.2.0 及其更高版本中,activated 和 deactivated 將會在 <keep-alive> 樹內的所有嵌套組件中觸發。
 
使用方法包括以下幾種:
 
1)基本用法:使用keep-alive直接包裹組件
   <keep-alive>
       <component :is="view"></component>
   </keep-alive> 
   <keep-alive> 包裹動態組件時,會緩存不活動的組件實例,而不是銷毀它們。
   如果需要緩存整個項目,則如下設置:
   <keep-alive>
      <router-alive> </router-view>
   </keep-alive>
 
2)緩存部分頁面或者組件,使用route.meta屬性
     在 App.vue中改造如下
    <keep-alive>
       <router-view v-if="$route.meta.keepAlive"></router-view>
   </keep-alive>
   <router-view v-if="!$route.meta.keepAlive"></router-view>
 
     項目中router中緩存頁面路由設置:
    {
        name: 'category',
        path: '/tingshu/category',
        component: Category,
         meta: { keepAlive: true }
    } 
    //Category組件使用keep-alive,將保存在內存中。
 
3)使用新增屬性include/exclude
     vue2.1.0 新增了include,exclude倆個屬性,允許組件有條件的緩存。二者都可以用逗號分隔字符串、正則表達式或一個數組來表示。
    <!-- 逗號分隔字符串 -->
    <keep-alive include="a,b">
         <component :is="view"></component>
    </keep-alive>
 
    <!-- 正則表達式 (使用 `v-bind`) -->
    <keep-alive :include="/a|b/">
        <component :is="view"></component>
    </keep-alive>
 
    <!-- 數組 (使用 `v-bind`) -->
    <keep-alive :include="['a', 'b']">
        <component :is="view"></component>
    </keep-alive>
   匹配首先檢查組件自身的 name 選項,如果 name 選項不可用,則匹配它的局部注冊名稱 (父組件 components 選項的鍵值)。匿名組件不能被匹配。
   
4)動態判斷,使用v-bind:include
    <keep-alive :include="includedComponents">
        <router-view></router-view>
    </keep-alive>
 includedComponents動態設置即可  
 
5)使用beforeRouteLeave或者afterEach中進行攔截處理
     如在項目在Category組件中的設置:
      

     在beforeRouteLeave中to.name根據具體的路由進行動態緩存設置。 

 

keep-alive的基本介紹完畢,如有紕漏還請多指教。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM