定義
Keep-alive是Vue內置的一個組件,可以使唄包含的組件保留狀態,或避免重複渲染。
其有兩個屬性:include(包含的組件緩存)與exclude(排除的組件 不緩存,優先級大於include)
使用方法
<keep-alive include="include_components" exclude="exclude_components">
<component></component>
</keep-alive>
參數解釋
include – 字符串或者正則表達式,只要名稱匹配的組件就會被緩存
exclude – 字符串或者正則表達式,只要名稱匹配的組件就不會被緩存,優先級高於include
include和exclude的屬性允許組件有條件的緩存。而且可以用“,”分割字符串、正則表達式、數組。但是使用正則或者是數組,要記得用v-bind,或者“:”
示例
<!-- 使用,分割字符串,只有組件a與b被緩存 -->
<keep-alive include="a,b">
<component></component>
</keep-alive>
<!-- 正則表達式,需要使用v-bind或者:,符合匹配規則的都會被緩存 -->
<keep-alive include="/a|b/">
<component></component>
</keep-alive>
<!-- 數組,需要使用v-bind或者:,只要被包含的都會被緩存 -->
<keep-alive include="['a','b']">
<component></component>
</keep-alive>