一、缓存全部路由:
<keep-alive >
<router-view ></router-view>
</keep-alive>
二、缓存指定路由:
- include
<keep-alive :include="该路由组件name”>
<router-view ></router-view>
</keep-alive>
- 使用meta:
(1). 路由中做如下配置:
{
path: '/A',
component:resolve => require(['../components/A'], resolve)
meta: { requiresAuth: true, title: "标题",keepAlive:true },
},
(2). 在APP.vue中:
<keep-alive >
<router-view v-if="$route.meta.keepAlive" ></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" ></router-view>
三、include和meta区别:
- 路由中使用meta只缓存第一次缓存下来的信息。
- 如果想实现从指定路由进入当前页面才做缓存keep-alive include比较合适。例如有三个组件A,B,C(假设A,B,C即为组件名字,又是路由名字,又是组件name),要求只有从A组件返回或者进入C组件时,才缓存C组件,代码如下:
(1). store.js中
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
cacheRoute: ['C']
},
mutations: {
'CACHEROUTE': (state, data) => {
state.cacheRoute = data;
},
}
})
(2). APP.vue中
<keep-alive :include="cacheRoute" >
<router-view ></router-view>
</keep-alive>
computed:{
cacheRoute(){
return this.$store.state.cacheRoute
}
}
(3). C页面中:
beforeRouteEnter(to, from, next) {
next(vm => {
vm.$store.commit('CACHEROUTE',['C'])//C为C组件的名字
});
},
beforeRouteLeave(to,from,next){
if(to.path!='/A'){
this.$store.commit('CACHEROUTE',[''])
}
next();
},
网友评论