需求说明:A页面到B页面需要缓存,A页面到C页面不需要缓存
所要缓存页面的顶级出口
<keep-alive :include="kpAlive"> <router-view/> </keep-alive> <script> export default { computed: { /** * router-alive */ kpAlive() { return this.$store.getters.kpAliveRouter; } } } </script>store
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: { kpAliveRouter: [] }, mutations: { //aliveRouter SET_KEEP_ALIVE: (state, keepAlive) => { state.kpAliveRouter = keepAlive; }, }, getters: { kpAliveRouter: state => state.kpAliveRouter } }) export default store;所要缓存的页面A
<script> const outAliveList = ['B'] const currentName= "A" export default { name: "A", beforeRouteEnter(to, from, next) { next(vm => { //进入默认缓存,hack:刷新后第一次不会缓存 vm.$store.commit("SET_KEEP_ALIVE", [currentName]); }); }, beforeRouteLeave(to, from, next) { //所要跳转的页面是需要缓存的B则进行缓存 if (outAliveList.includes(to.name)) { this.$store.commit("SET_KEEP_ALIVE", [currentName]); } else { this.$store.commit("SET_KEEP_ALIVE", []); } next(); }, } </script>tips: 1.此处的A为页面中name的值,不为route的name 2.如果没有达到缓存A页面效果,则需要检查A页面是否在二级(多级)的keep-alive中,如是则需要同时缓存这些层级页面