<keep-alive>
包裹動態組件時,會緩存不活動的組件實例,而不是銷毀它們。
<keep-alive>
是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出現在父組件鏈中,不會渲染到DOM樹中。
它的作用是在內存中緩存組件(不讓組件銷毀),等到下次渲染是,還會保留在原來的狀態。
當組件在 <keep-alive>
內被切換,它的 activated
和 deactivated
這兩個生命周期鈎子函數將會被對應執行。
使用:
<keep-alive include="mainList"> <router-view class="child-view"></router-view> </keep-alive>
keep-alive的屬性:
include - 字符串或正則表達式。只有名稱匹配的組件會被緩存。
exclude - 字符串或正則表達式。任何名稱匹配的組件都不會被緩存。
include 和 exclude 屬性允許組件有條件地緩存。二者都可以用逗號分隔字符串、正則表達式或一個數組來表示
max - 數字。最多可以緩存多少組件實例,一旦這個數字達到了,在新實例被創建之前,已緩存組件中最久沒有被訪問的實例會被銷毀掉。
keep-alive的鈎子函數:
activated 和 deactivate 生命周期鈎子:
設置了keepAlive緩存的組件:
activated deactivate 只要頁面切換加載組件就會執行一次
第一次進入:beforeRouterEnter -> created -> … ->activated-> … ->deactivated
后續進入時:beforeRouterEnter -> activated -> deactivated
如果每次進入組件,需要更新某些數據,此時需要把這些方法寫在 actived 中
當離開組件時,需要終止某些方法,需要在 deactivated 操作,比如:進入頁面發起ajax,在ajax的加載沒有完成時退出該頁面,此時就需要將 loading(我的ajax 和 loading 是分別控制的) 置為 false
結合 router 緩存部分組件
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive></router-view>
route元信息:
routers: [{ path: '/', name: 'Home', meta: { keepAlive: false // 不需要緩存 } },{ path: '/page', name: 'Page', meta: { keepAlive: true // 需要緩存 } },]
route:
routers = [ { path: '/', name: 'home', component: Home, redirect: { path: '/' }, children: [{ path: '/', name: 'index', component: List, // 列表頁 meta: { isUseCache: false,// 是否需要緩存 keepAlive: true // 緩存 } }, { path: '/detail1', name: 'detail1', component: Detail1, // 詳情頁 meta: { keepAlive: false } // 不緩存 }] } ]
在列表頁的 activated beforeRouteLeave 鈎子中:
activated() { // isUseCache為false,重新刷新獲取數據 if(!this.$route.meta.isUseCache){ this.list = []; // 清空原有數據 this.onLoad(); // 這是我們獲取數據的函數 } }, beforeRouteLeave (to, from, next) { // 如果去詳情頁,就緩存 列表頁面數據 if (to.name == 'Detail') { from.meta.isUseCache = true; } next(); },
那么如果在詳情頁面的訂單狀態發生改變,那么返回列表頁面就需要刷新了。
那么詳情頁面的路由可以這樣:
data() { return { isDel: false // 是否進行了刪除訂單的操作 } }, beforeRouteLeave (to, from, next) { if (to.name == 'List') { // 根據是否刪除了訂單的狀態,進行判斷list是否需要使用緩存數據 to.meta.isUseCache = !this.isDel; } next() }, methods: { deleteOrder () { // 刪除訂單的操作 code ... this.isDel = true; this.$router.go(-1) } }