keep-alive 缓存不更新问题

使用keep-alive经常会遇见的需求,从a页面进入b页面时不需要缓存,b页面进入c页面时候,b页面需要缓存

1、首页我们需要在vuex中定义一个字段来判断是否需要缓存,字段为需要缓存的组件名

const state = {
	catch_components:['b']
};
const mutations={
	GET_CATCHE_COMPONENTS (state, data) {
	      state.catch_components = data
	}
};

2、在app.vue中写上keep-alive,把用vuex中的字段控制是否缓存

<keep-alive :include="catch_components">
		      <router-view />
</keep-alive>

computed: {
      catch_components () {
        return this.$store.state.catch_components
      }
}

3、在b页面上导航守卫上监听页面

beforeRouteEnter  (to, from, next) {
			 next(vm=>{
				 vm.$store.commit('GET_CATCHE_COMPONENTS', ['b'])//必须要这一步,否则缓存有可能回不更新
			 })
},
beforeRouteLeave (to, from, next) {
		    if (to.path === '/c') { // 去往c页的时候需要缓存组件,其他情况下不需要缓存
		      	 this.$store.commit('GET_CATCHE_COMPONENTS',['b'])//b为组件名称(name)
		        } else {
		          this.$store.commit('GET_CATCHE_COMPONENTS', [])
		        }
	next()
},

猜你喜欢

转载自blog.csdn.net/sxmzhw/article/details/126283878