vue中keep-alive的使用
阿新 • • 發佈:2020-07-01
在vue2.1.0版本後,keep-alive新加入了兩個屬性:include(包含的元件快取生效)與exclude(排除的元件不快取,優先順序大於include)。
include和exclude屬性允許元件有條件的快取。二者都可以用逗號分隔字串、正則表示式或一個數組來表示。(當使用正則或者是陣列時,一定要使用v-bind)
<!-- 逗號分隔字串,只有元件a與b被快取。這樣使用場景變得更有意義了 --> <keep-alive include="a,b"> <component :is="view"></component> </keep-alive> <!-- 正則表示式 (需要使用 v-bind,符合匹配規則的都會被快取) --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> <!-- Array (需要使用 v-bind,被包含的都會被快取) --> <keep-alive :include="['a', 'b']"> <component :is="view"></component> </keep-alive>
有了include之後,再與router-view一起使用時便方便了許多了:
<!-- 一個include解決了,不需要多寫一個標籤,也不需要在路由元中新增keepAlive了 --> <keep-alive include='a'> <router-view></router-view> </keeo-alive>
需要注意的地方:
1、<keep-alive>先匹配被包含元件的name欄位,如果name不可用,則匹配當前元件components配置中的註冊名稱。
2、<keep-alive>不會在函式式元件中正常工作,因為他們沒有快取例項。
3、當匹配條件同時在include與exclude存在時,以exclude優先順序最高
4、包含在<keep-alive>中,但符合exclude,不會呼叫activated和deactivated。