1.app.vue
<template>
<div class="app">
<keep-alive :include="keepAlive" >
<router-view/>
</keep-alive>
</div>
</template>
<script type='text/javascript'>
export default {
data () {
return {}
},
computed: {
keepAlive () {
return this.$store.getters.keepAlive
}
}
}
</script>
2.store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAlive: []
},
mutations: {
SET_KEEP_ALIVE: (state, keepAlive) => {
state.keepAlive = keepAlive
}
},
getters: {
keepAlive: state => state.keepAlive
}
})
3.第一个页面.vue
<script>
export default {
name: 'A',
methods: {
buttonClick () {
this.$store.commit('SET_KEEP_ALIVE', ['B', 'C', 'D'])
this.$router.push('/B')
}
}
}
</script>
4.第二个页面.vue
<script>
export default {
name: 'B',
beforeRouteEnter (to, from, next) {
next(vm => {
if (from.path.indexOf('C') > -1) {
vm.$store.commit('SET_KEEP_ALIVE', ['B'])
}
})
},
beforeRouteLeave (to, from, next) {
if (to.path.indexOf('C') > -1) {
this.$store.commit('SET_KEEP_ALIVE', ['B', 'C'])
} else if (to.path.indexOf('A') > -1) {
this.$store.commit('SET_KEEP_ALIVE', [])
}
next()
}
}
</script>