vue3.0中的keep-alive使用及說明
keep-alive
用法
keep-alive是vue中的一個內(nèi)置組件,通常用它來包裹一個動態(tài)組件,keep-alive 包裹動態(tài)組件時,會緩存不活動的組件實例,而不是銷毀它們。
它有兩個特殊的生命周期鉤子activated 和 deactivated,在vue3.0里面生命周期函數(shù)前面都要加上on,onActivated,onDeactivated。
當組件在使用了keep-alive包裹時,正常的生命周期函數(shù)mounted和unmounted將不會執(zhí)行,取而代之的是為它新增的這個兩個特殊鉤子函數(shù)。
vue3.0生命周期圖:
屬性
include
:只有名稱匹配的組件會被緩存;類型可以是數(shù)組、字符串或者正則。exclude
:名稱匹配的組件不會被緩存;類型可以是數(shù)組、字符串或者正則。max
:最多可以緩存多少組件實例。
vue3中使用
vue3中的寫法和vue2中稍微有點不同,具體代碼可以參考下方:
<router-view v-slot="{ Component, route }" id="pageWrapper"> <transition :name="transitionName" mode="out-in"> <keep-alive :include="cacheRouter"> <component :is="Component" /> </keep-alive> </transition> </router-view>
設(shè)置被緩存的路由 可以直接寫死,把需要緩存的路由name寫到一個數(shù)組中,這樣最簡單粗暴,不過不靈活,不建議使用這種方式
cacheRouter: ['home', 'order'];
通過設(shè)置路由原信息
在需要被緩存的組件的meta里面添加keepAlive標記
export const routes: RouteRecordRaw[] = [ { path: '/myLogin', name: 'myLogin', component: () => import('@/views/login/login.vue'), meta: { title: '登錄', index: 1, keepAlive: true, }, }, ]; let cacheList: any[] = []; const keepAliveView = (_route: RouteRecordRaw[], _cache: RouteRecordName[]): void => { _route.forEach((item) => { item.meta?.keepAlive && item.name && _cache.push(item.name); }); }; //routes 路由配置數(shù)組 keepAliveView(routes, cacheList); export default cacheList;
vue3.0與vue2.0中keep-alive的用法區(qū)別
vue2.0
? ? <keep-alive> ? ? ? <router-view /> ? ? </keep-alive>
vue3.0
? ? <suspense> ? ? ? <router-view v-slot="{ Component }"> ? ? ? ? <keep-alive> ? ? ? ? ? <component :is="Component" /> ? ? ? ? </keep-alive> ? ? ? </router-view> ? ? </suspense>
注意點
如果 router-view 嵌套的子組件里面還有router-view, 那么子組件里面也要加上keep-alive
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3實現(xiàn)動態(tài)導入Excel表格數(shù)據(jù)的方法詳解
在開發(fā)工作過程中,我們會遇到各種各樣的表格數(shù)據(jù)導入,動態(tài)數(shù)據(jù)導入可以減少人為操作,減少出錯。本文為大家介紹了Vue3實現(xiàn)動態(tài)導入Excel表格數(shù)據(jù)的方法,需要的可以參考一下2022-11-11使用echarts點擊按鈕從新渲染圖表并更新數(shù)據(jù)
這篇文章主要介紹了使用echarts點擊按鈕從新渲染圖表并更新數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10unplugin-auto-import與unplugin-vue-components安裝問題解析
這篇文章主要為大家介紹了unplugin-auto-import與unplugin-vue-components問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02