vuex keep-alive动态缓存

理论网上有很多大神已经讲得很清楚,我就不赘述啦,这里我主要记录下自己的实操,作为项目总结,也便于自己以后查阅。

需求:页面顺序,从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只要页面切换加载组件就会执行一次。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值