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保留页面数据。希望对大家有所帮助!

Supongo que te gusta

Origin blog.csdn.net/qq_36229632/article/details/103977500
Recomendado
Clasificación