需要實現的場景
當 A頁面除了返回上級頁面以外,跳到其他頁面均緩存A頁面內容
實現思路
- 使用keep-alive的include屬性,將需要緩存的頁面加入include數組中
- 使用vuex保存需要緩存的頁面集合
- 在頁面跳轉時使用導航守衛判斷路由跳轉頁面
- 調用vux中的方法修改include集合
代碼實現如下
App.vue
<template>
<keep-alive :include="keepAlive" >
<router-view/>
</keep-alive>
</template>
<script>
export default {
data() {
return {}
},
computed: {
keepAlive() {
return this.$store.state.keepAlive.join(',')
}
}
}
</script>
Store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAlive: []
},
mutations: {
onKeepAlive (state, keepAlive) {
state.keepAlive = keepAlive
}
},
actions: {
onKeepAlive ({ commit }, keepAlive) {
commit('onKeepAlive', keepAlive)
}
}
})
A.vue
beforeRouteLeave(to, from, next) {
if (to.path.indexOf('B') == -1) {
this.$store.dispatch('onKeepAlive', ['A'])
}
next()
}
//判斷跳轉路由是否爲B,爲B不緩存,其他頁面均緩存A頁面