在 store 下新建 cachedViews.js
const state = {
cachedViews: []
}
const mutations = {
ADD_CACHED_VIEW: (state, view) => {
if (state.cachedViews.includes(view.name)) return
if (view.meta.keepAlive) {
state.cachedViews.push(view.name)
}
}
}
const actions = {
addCachedView({ commit }, view) {
commit('ADD_CACHED_VIEW', view)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
在AppMain里监听路由改变设置keep-alive
include缓存(include包含的是template组件的名字,要和路由name一致)
export default {
name: 'AppMain',
computed: {
key() {
return this.$route.path
},
cachedViews() {
return this.$store.state.cachedViews.cachedViews
}
},
watch: {
$route() {
this.addCachedView()
}
},
mounted() {
this.addCachedView()
},
methods: {
addCachedView() {
const { name } = this.$route
if (name) {
this.$store.dispatch('cachedViews/addCachedView', this.$route)
}
return false
}
}
}