1. 程式人生 > >關於vue的特殊屬性keep-alive

關於vue的特殊屬性keep-alive

  1. <keep-alive> 包裹動態元件時,會快取不活動的元件例項,而不是銷燬它們。和 <transition> 相似,<keep-alive> 是一個抽象元件:它自身不會渲染一個 DOM 元素,也不會出現在父元件鏈中。當元件在 <keep-alive> 內被切換,它的 activated 和 deactivated 這兩個生命週期鉤子函式將會被對應執行。
  2. 在 2.2.0 及其更高版本中activated和 deactivated將會在<keep-alive>樹內的所有巢狀元件中觸發主要用於保留元件狀態或避免重新渲染。
  3. 注意,<keep-alive>
     是用在其一個直屬的子元件被開關的情形。如果你在其中有 v-for 則不會工作。如果有上述的多個條件性的子元素,<keep-alive> 要求同時只有一個子元素被渲染。
              
<!-- 基本 -->
<keep-alive>
  <component :is="view"></component>
</keep-alive>

<!-- 多個條件判斷的子元件 -->
<keep-alive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b
v-else>
</comp-b>
</keep-alive> <!-- 和 `<transition>` 一起使用 --> <transition> <keep-alive> <component :is="view"></component> </keep-alive> </transition>

  • include 和 exclude 屬性允許元件有條件地快取。二者都可以用逗號分隔字串、正則表示式或一個數組來表示。配首先檢查元件自身的 name 選項,如果 name
     選項不可用,則匹配它的區域性註冊名稱 (父元件 components 選項的鍵值)。匿名元件不能被匹配。<keep-alive> 不會在函式式元件中正常工作,因為它們沒有快取例項。
<!-- 逗號分隔字串 -->
<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>