业务场景:从a组件跳转到b组件,再返回a组件,数据状态保持不变,比如表格的页数
1. 利用Vuex,保存需要缓存的组件的"组件名"
import Vue from 'vue'
import Vuex from 'vuex'
const state = {
keepAlive: []
}
const mutations = {
SET_KEEPALIVE: (state, name) => {
const index = state.keepAlive.indexOf(name)
if (index === -1) {
state.keepAlive.push(name)
}
},
REMOVE_KEEPALIVE: (state, name) => {
const index = state.keepAlive.indexOf(name)
if (index > -1) {
state.keepAlive.splice(index, 1)
}
}
}
const actions = {
setKeepAlive({
commit }, name) {
commit('SET_KEEPALIVE', name)
},
removeKeepAlive({
commit }, name) {
commit('REMOVE_KEEPALIVE', name)
}
}
Vue.use(Vuex)
const store = new Vuex.Store({
state,
mutations,
actions
}
export default store
new Vue({
store,
}).$mount('#app')
2. 组件内调用beforeRouteEnter,beforeRouteLeave控制组件是否进行数据保持
export default {
name: 'A',
beforeRouteEnter(to, from, next) {
if (from.path !== 'b组件路由路径') {
store.dispatch('removeKeepAlive', 'A')
}
next()
},
beforeRouteLeave(to, from, next) {
if (to.path === 'b组件路由路径') {
store.dispatch('setKeepAlive', 'A')
}
next()
},
}
3. 使用缓存路由组件,让不展示的组件保持挂载不被销毁
<keep-alive :include="this.$store.state.app.keepAlive">
<router-view :key="key" />
</keep-alive>