keep-alive用法:
1、在app.vue中定義keep-aliv
<router-view v-if="!$route.meta.keepAlive"></router-view> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive>
2、在路由文件router.js中,定義meta信息
{ path: '/space4', name: 'space4', component: () => import( './components/workspace/space4.vue'), meta: { isUseCache: false, // 默認不緩存 keepAlive: true, } }
3、列表頁的activated鈎子
activated() { if(!this.$route.meta.isUseCache){ //isUseCache 時添加中router中的元信息,判讀是否要緩存 this.contactList = [] //清空原有數據 this.contactDisplay() // 重新加載 } }, methods: { onClickLeft() { this.$router.go(-1) }, contactDisplay() { this.contactListGet = JSON.parse(sessionStorage.getItem('contact-item')) let personal = this.contactListGet let i = 0 for(i in personal) { // let surname = personal[i].substring(0,1) let surname = personal[i].substring(personal[i].length-2) this.contactList.push({'surname': surname, name: personal[i]}) } console.log('contactList', this.contactList) } }
4、詳細頁面 beforeRouteLeave的鈎子函數
beforeRouteLeave(to, from, next){ // 列表頁面跳轉到 詳情頁時,設置需要緩存 if(to.name=='spaceContact'){ from.meta.isUseCache = true } next() }
vue鈎子函數:
設置了keepAlive緩存的組件:
第一次進入:beforeRouterEnter ->created->…->activated->…->deactivated
后續進入時:beforeRouterEnter ->activated->deactivated 可以看出,只有第一次進入該組件時,才會走created鈎子,而需要緩存的組件中activated是每次都會走的鈎子函數。所以,我們要在這個鈎子里面去判斷,當前組件是需要使用緩存的數據還是重新刷新獲取數據。