一、页面打开顺序
页面顺序: | A菜单 | A详情1 | A详情2 |
---|---|---|---|
从 A菜单 ->A详情2缓存: | A 打开 详情1 | 详情1 打开 详情2 | 详情2 打开 |
缓存 A | 缓存 详情1 | 缓存 详情2 | |
详情1获取新数据 | 详情2获取新数据 | ||
从详情2-> A菜单 缓存: | 详情2 返回 详情1 | 详情1 返回 A菜单 | |
显示详情1的缓存 | 显示A菜单的缓存 |
二、路由
const Routers =[
{
path: "/AMenu",
name: "AMenu",
meta: {
title: "A菜单",
keepAlive:true,
isRoot:true //是否菜单
},
component: resolve => require(["@/views/AMenu/index"], resolve)
},
{
path: "/BMenu",
name: "BMenu",
meta: {
title: "B菜单",
keepAlive:true,
isRoot:true //是否主菜单
},
component: resolve => require(["@/views/BMenu/index"], resolve)
},
{
path: "/AMenuDetail1",
name: "AMenuDetail1",
meta: {
title: "详情1",
keepAlive:true
},
component: resolve => require(["@/views/AMenuDetail1/index"], resolve)
},
{
path: "/AMenuDetail2",
name: "AMenuDetail2",
meta: {
title: "详情2",
keepAlive:true
},
component: resolve => require(["@/views/AMenuDetail2/index"], resolve)
},
]
三、状态
const store = new Vuex.Store({
state: {
cachedRoutes: [],
},
mutations: {
addCachedRoutes(state, route) {
if (!state.cachedRoutes.includes(route.name)) {
if (route.meta.noKeepAlive) {
state.cachedRoutes.push(route.name)
}
}
},
delCachedRoutes(state, route) {
for (const i of state.cachedRoutes) {
if (i === route.name) {
const index = state.cachedRoutes.indexOf(i)
state.cachedRoutes.splice(index, 1)
break
}
}
},
},
actions = {
addCachedRoutes({ commit }, route) {
commit('addCachedRoutes', route)
},
delCachedRoutes({ commit, state }, route) {
return new Promise((resolve) => {
commit('delCachedRoutes', route)
resolve([...state.cachedRoutes])
})
},
}
})
四、界面
html代码:
<keep-alive :include="cachedRoutes">
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
js代码:
export default {
name: "App",
data() {
return {}
},
computed:{
...mapGetters({
cachedRoutes: 'cachedRoutes',
}),
},
created(){
//监听页面刷新
window.addEventListener('beforeunload',function(){
//监听刷新默认缓存当前组件
that.$store.commit('addCachedRoutes',that.$route);
})
}
}
五、修改路由中 scrollBehavior 滚动行为
new Router({
// mode: 'history',
scrollBehavior: (to, from, savedPosition) => {
//坐标有值表示后退
if (savedPosition) {
store.dispatch('delCachedRoutes', from)
//后退滚动到上一次位置
if (savedPosition) {
return savedPosition
}
} else {
//前进把前进的页面加入到要缓存的组件中
store.dispatch('addCachedRoutes', to)
//菜单之间切换是不需要缓存的,因为大家都是同级页面
if (to.meta.isRoot && from.meta.isRoot) {
store.dispatch('delCachedRoutes', from)
}
//前进滚动到顶部
return { x: 0, y: 0 }
}
},
})