概述:vue開發項目時,需要緩存多個頁面的情況
使用場景:例如:現有4個頁面,頁面1,頁面2,頁面3,頁面4
要求:1、從1-2-3-4依次跳轉時,每次都刷新頁面,不進行緩存;
2、從4-3-2-1依次返回時,頁面不刷新,依次取緩存頁面;
總結:外到內都需要刷新,內到外皆獲取緩存頁面;
實現方式:keep-alive、vuex、路由鈎子函數beforeRouteEnter、beforeRouteLeave
具體實現方式代碼:
1、vuex部分:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { keepAlive: [] }, mutations: { CHANGE_KEEPALIVE: (state, keepAlive) => { state.keepAlive = keepAlive } }, // 這里getters可有可無 getters: { keepAlive: state => state.keepAlive } }); export default store;
2、app.vue內部寫法
<template>
<div id="app">
<!-- 當使用了getters和computed進行監聽時,可直接綁定keepAlive -->
<keep-alive :include="keepAlive" >
<!-- 也可不使用getters和computed進行監聽,直接取值$store.state.keepAlive -->
<!-- <keep-alive :include="$store.state.keepAlive" > -->
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
name: "app",
data() {
return {};
},
// 當使用了getters時可以選擇添加computed進行監聽
computed: {
keepAlive() {
return this.$store.getters.keepAlive;
},
},
};
</script>
3、頁面1內部寫法
beforeRouteEnter (to, from, next) { next(vm => { vm.$store.commit('CHANGE_KEEPALIVE', ['頁面1']) }) }, // 跳轉 goLink(){ this.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2','頁面3']) this.$router.push({ path:'/頁面2', }) },
4、頁面2內部寫法
beforeRouteEnter (to, from, next) { next(vm => { if (from.path.indexOf('頁面3') > -1) { vm.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2']) } }) }, beforeRouteLeave (to, from, next) { if (to.path.indexOf('頁面3') > -1) { this.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2', '頁面3']) } else if (to.path.indexOf('頁面1')>-1) { this.$store.commit('CHANGE_KEEPALIVE', ['頁面1']) } next() },
5、頁面3內部寫法
beforeRouteEnter (to, from, next) { next(vm => { if (from.path.indexOf('頁面4') > -1) { vm.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2', '頁面3']) } }) }, beforeRouteLeave (to, from, next) { if (to.path.indexOf('頁面4') > -1) { this.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2', '頁面3']) } else if (to.path.indexOf('頁面2') > -1) { this.$store.commit('CHANGE_KEEPALIVE', ['頁面1','頁面2']) } next() },
6、頁面4不需要緩存則無需添加任何東西,正常書寫即可,如需添加設置緩存,則按照上方更改添加配置即可
