vue 部分页面缓存,部分页面不缓存的问题

前端时间项目迭代,其中有个需求

在vue里面,有a.b.c三个页面,要达到的效果是从a页面进去b页面,b页面需要刷新,但若从b页面进入c页面了以后再回到b页面,b页面需要保留之前的值,不做刷新;

第一想到的是:<router-view v-if="$route.meta.keepAlive"></router-view> ;但是由于v-if 每次会销毁页面元素,导致第一次是缓存不成功的;在网上也找到过window.reload();这种方法,但是页面会有一瞬间的空白,用户体验不是很好;

后同事找了一种方法,vuex结合路由守卫可以达到此效果,具体代码如下:

首先app.vue

//js

computed: {
                        keepAlive () {
                                return this.$store.getters.keepAlive
                        }
                },

//html
<keep-alive  :include='keepAlive'>
        <router-view></router-view>
</keep-alive>

vuex 中需要定义keepAlive

import Vue from 'vue'
import Vuex from 'vuex'


Vue.use(Vuex)

var store = new Vuex.Store({
    // 定义状态
    state: {
        
        keekAlives:[],
        
    },
    mutations:{  //更改 Vuex 的 store 中的状态
        SET_KEEP_ALIVE:function(state, keekAlives){
           return state.keekAlives = keekAlives;
        }
    },
    getters: {
      keepAlive: function(state){
          return state.keekAlives
    //   keepAlive: state => state.keekAlives
      }
    }
})

export default store

最后在需要缓存的页面进行判断

beforeRouteEnter (to, from, next) {
     next(vm => {
               if (from.name=="serve") {
                    vm.$store.commit('SET_KEEP_ALIVE', ['addProject'])
               }
            })
        },
        beforeRouteLeave (to, from, next) {
            if (to.name == "companySearch") {
               this.$store.commit('SET_KEEP_ALIVE', ['addProject'])
            } else if (to.name=="serve" || to.name=="addSuccess") {
         this.$store.commit('SET_KEEP_ALIVE', []) 
            }
            next()
        },