vue中的keep-alive

官方文檔:html

keep-alive

若是把切換出去的組件保留在內存中,能夠保留它的狀態或避免從新渲染。爲此能夠添加一個 keep-alive 指令參數:vue

<keep-alive>
  <component :is="currentView">
    <!-- 非活動組件將被緩存! -->
  </component>
</keep-alive>
  • Props:正則表達式

    • include - 字符串或正則表達式。只有匹配的組件會被緩存。
    • exclude - 字符串或正則表達式。任何匹配的組件都不會被緩存。
  • 用法:數組

    <keep-alive> 包裹動態組件時,會緩存不活動的組件實例,而不是銷燬它們。和 <transition> 類似,<keep-alive> 是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出如今父組件鏈中。緩存

    當組件在 <keep-alive> 內被切換,它的 activated 和 deactivated 這兩個生命週期鉤子函數將會被對應執行。ide

    在 2.2.0 及其更高版本中,activated 和 deactivated 將會在 <keep-alive> 樹內的全部嵌套組件中觸發。函數

2.1.0 新增:include 和 exclude 屬性容許組件有條件地緩存。兩者均可以用逗號分隔字符串、正則表達式或一個數組來表示:ui

<!-- 逗號分隔字符串 -->
<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 選項的鍵值)。匿名組件不能被匹配。spa

<keep-alive> 不會在函數式組件中正常工做,由於它們沒有緩存實例。code

動態判斷
<keep-alive :include="includedComponents">
  <router-view></router-view>
</keep-alive>

includedComponents動態設置便可

在2.1.0以前,咱們能夠這樣作:

緩存部分頁面或者組件

(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設置
 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
參考連接:http://www.jianshu.com/p/e4bd12e789dd
相關文章
相關標籤/搜索