vue中keep-alive 前进后退时页面数据缓存和刷新问题
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是每次都会走的钩子函数。所以,我们要在这个钩子里面去判断,当前组件是需要使用缓存的数据还是重新刷新获取数据。