前言
今天顺便总结一下前几天项目中遇到的一个问题,总的来说就是前进刷新,后退不刷新的一个缓存设置;好处是每次都返回页面时,不会重新请求数据。
我用到了KeepAlive,顺便更深入的解了vue的router以及他的导航守卫,另外还用到了vuex。接下来复习一下如何做到的。
keepalive组件-缓存
keepalive官网:主要用于保留组件状态或避免重新渲染,详细内容可进官网查看,这里不多说。具体是如何操作的来看一下。
大体来讲,其实每个页面都可以加上keepAlive组件来保持当前状态,所以我在最vue根源页面添加了keepAlive组件即app.vue。这样不管是哪个页面需要这种设置都可以。
简单了解一下keepAlive执行顺序
- 第一次进入keepAlive时:beforeCreate > created > beforeMount > mounted > activated > beforeRouteLeave > deactivated
- 第二次进入keepAlive时:activated> beforeRouteLeave > deactivated
思路
我们用index和home(缓存页面)两个页面进行试验,home进入index页面(前进)不缓存,index返回home(后退)缓存。
此组件第一次进入会缓存当前页面的状态,keepAlive=true,isBack=true,如果需要改变此页面的,则只需要改变路由里的keepAlive为false就不会进入到缓存页面。
<template>
<div id="app" style="width: 100%">
<!--具体用的时候会发现,此组件只会缓存第一次进入页面的状态,若需要改变当前页面,再次进入-->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"/>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"/>
</div>
</template>
我们可以看到有$route.meta.keepAlive这么一句话,肯定要收拾我们的路由。
routes = [
{
path:'/index',
name:'index',
component:()=>import('./views/index.vue'),
//需要我们为需要缓存的路由添加
meta:{
keepAlive:false //不需要缓存
}
},
{
path:'/home',
name:'home',
component:()=>import('./views/home.vue'),
meta:{
keepAlive:true, //需要缓存
isBack:false //判断是返回到这个页面了还是前进到这个页面了
}
}
]
home.vue
<!--home-->
<script>
import {mapActions} from 'vuex'
export default {
name:'home',
data(){
return{
datas:{}
}
},
methods:{
...mapActions('home',['setData']),
commit(){
this.$router.push({name:'inidex'})
}
},
activated(){
//第一次进入时isBack=false,所以就不从vuex里拿了
if(this.$route.meta.isBack){
//如果进入到缓存,且isBack是true,就从vuex里拿数
this.text=this.$store.state.home.data.text
}
},
beforeRouteLeave(to,form,next){
//判断home进入的页面,每次离开这个页面,记录下离开时数据
if(to.name=='index'){
from.meta.keepAlive=true
//储存当前页面信息
let data={
datas:this.datas
}
this.setData(data);
}else{
from.meta.keepAlive=false,//解除缓存
from.meta.isBack=false
}
next()
}
deactivated(){
}
}
</script>
<style>
...
</style>
<script>
export default {
name:'index',
data(){
return{
title:'This is Index.vue',
isBack:false
}
},
methods:{
todo(){
//如果想更新缓存页的内容的话
this.isBack=false
},
returnBack(){
this.isBack=true
this.$router.go(-1)
}
},
beforeRouteLeave(to,from,next){
if(this.isBack){
to.meta.keepalive=true
to.meta.isBack=true
}else{
to.meta.keepalive=false
to.meta.isBack=false
}
next()
}
}
</script>
以上就是缓存vue组件的方法,仅供参考。