keep-alive+vuex实现页面数据缓存

在使用VUE开发项目时,从列表页跳转到详情页后。每次返回会发现列表页都会进行重载。尤其是在列表页涉及到tab切换时,重载后用户还需要再次操纵切换。体验度大大降低。

可以选用keep-alive 里的include+VUEX进行动态缓存

如:从A>B>C页面时候,让页面刷新。从C>B>A时候让B禁止刷新。也就是需要将B页面存入缓存中。

实现:首先需要在A/B/C各自的单页面中命名name。这里可以先命名成A、B、C.

APP.VUE

//APP.VUE
<keep-alive :include="keepAlive" >
      <router-view/>
</keep-alive>

export default {
	name: 'App',
	computed: {
	    keepAlive () {
	      return this.$store.getters.keepAlive
	    }
  },
}

store.js

import Vue from 'vue'
import Vuex from 'vuex'
export default new Vuex.Store({
    state: {
        keepAlive: []
    },
    mutations: {
        setKeepAlive: (state, keepAlive) => {
            state.keepAlive = keepAlive;
        }
    },
    getters: {
        keepAlive: state => state.keepAlive
    }
});

A.VUE

//监听路由离开
export default {
  name: "A",
  components: { countTo },
  beforeRouteLeave (to, from, next) {
      this.$store.commit('setKeepAlive', ['B'])
      next()
  }
  },

B.VUE

export default {
  name: "B",
  components: { countTo },
  beforeRouteLeave (to, from, next) {
  //判断要进入的页面是不是C,如果是C则给B进行缓存。
    if (to.name === 'C' ) {
      this.$store.commit('setKeepAlive', ['B'])
    } else {
      this.$store.commit('setKeepAlive', [])
    }
    next()
  },
  },

以上代码就可以实现B页面数据的缓存。但是如果B页面中有Tab切换。在切换后直接进入C页面,点击A页面,在点击进入B页面。会发现B页面的缓存还在。这时候我们需要在C页面也进行缓存清理。

C.VUE

export default {
  name: "C",
  components: { countTo },
  beforeRouteLeave (to, from, next) {
  //判断要进入的页面是不是B,则给B进行缓存。
    if (to.name === 'B' ) {
      this.$store.commit('setKeepAlive', ['B'])
    } else {
      this.$store.commit('setKeepAlive', [])
    }
    next()
  },
  },

按照已经代码执行,就会实现A>B>C 刷新页面请求数据。C>B保留页面数据。希望对大家有所帮助!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值