理论网上有很多大神已经讲得很清楚,我就不赘述啦,这里我主要记录下自己的实操,作为项目总结,也便于自己以后查阅。
需求:页面顺序,从A到B到C,对于B 页面,进入C页面时,需要缓存,进入A页面时,不需要缓存,A进入B的时候是要刷新的。所以,问题就是,如何让keep-alive 缓存动态进行?
思路就是:动态改变keep-alive的include数组。
在App.vue中
<div id="app">
<keep-alive :include="keepAliveComponents">
<router-view></router-view>
</keep-alive>
</div>
computed: {
keepAliveComponents: ()=>{
return store.state.keepAliveComponents;
}
}
store.js中
state: {
keepAliveComponents: []
},
mutations: {
keepAlive(state, component) {
// 注:防止重复添加(当然也可以使用Set)
!state.keepAliveComponents.includes(component) &&
state.keepAliveComponents.push(component);
},
noKeepAlive(state, component) {
const index = state.keepAliveComponents.indexOf(component);
index !== -1 &&
state.keepAliveComponents.splice(index, 1);
}
router.js 中,给需要用到keep alive的组件的meta标签中添加keepAlive属性
router.beforeEach((to, from, next) => {
// 在路由全局钩子beforeEach中,根据keepAlive属性,统一设置页面的缓存性
// 作用是每次进入该组件,就将它缓存
if (to.meta.keepAlive) {
store.commit('keepAlive', to.name);
}
next();
});
组件中使用
beforeRouteLeave (to, from, next) {
// 如果下一个页面不是分账户充值页,则取消充值页的缓存
if(to.name !== 'account'){
this.$store.commit('noKeepAlive', from.name);
}
next(); // next 方法不能忘记,不然程序不会往下走
}
这样就可以啦~
最后,有时候我们也需要缓存的页面刷新部分数据,这个时候我们可以使用钩子函数activated。因为mounted只执行一次,而activated只要页面切换加载组件就会执行一次。