keep-alive:主要用於保留組件狀態或避免重新渲染。
比如: 有一個列表頁面和一個 詳情頁面,那么用戶就會經常執行打開詳情=>返回列表=>打開詳情這樣的話 列表 和 詳情 都是一個頻率很高的頁面,那么就可以對列表組件使用<keep-alive></keep-alive>進行緩存,這樣用戶每次返回列表的時候,都能從緩存中快速渲染,而不是重新渲染。
1、屬性:
-
include:字符串或正則表達式。只有匹配的組件會被緩存。 -
exclude:字符串或正則表達式。任何匹配的組件都不會被緩存。
2、用法:
包裹動態組件時,會緩存不活動的組件實例,而不是銷毀它們。和 <transition>相似,<keep-alive>是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出現在父組件鏈中。
<!-- 基本 --> <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>
注意:<keep-alive>是用在其一個直屬的子組件被開關的情形。如果你在其中有 v-for 則不會工作。如果有上述的多個條件性的子元素,<keep-alive> 要求同時只有一個子元素被渲染。
3、include 和 exclude 屬性的使用:
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 選項的鍵值)。匿名組件不能被匹配。
