關於vue的特殊屬性keep-alive
阿新 • • 發佈:2019-01-31
<keep-alive>
包裹動態元件時,會快取不活動的元件例項,而不是銷燬它們。和<transition>
相似,<keep-alive>
是一個抽象元件:它自身不會渲染一個 DOM 元素,也不會出現在父元件鏈中。當元件在<keep-alive>
內被切換,它的activated
和deactivated
這兩個生命週期鉤子函式將會被對應執行。- 在 2.2.0 及其更高版本中,
activated
和deactivated
將會在<keep-alive>
樹內的所有巢狀元件中觸發。主要用於保留元件狀態或避免重新渲染。 - 注意,
<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-bv-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>