Vue动态缓存页面

原理通过keep-alive标签的include属性及vuex完成

需求说明: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中,如是则需要同时缓存这些层级页面

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值