1. 设置需要缓存的页面 keepAlive: true
{
path:
"/index",
name:
"index",
component:
() => import
("../views/index"),
meta:
{
keepAlive:
true
}
}
2. 全局监听后退事件设置 isBack 为true
// main.js
window.onpopstate
=function
(){
Vue.isBack
=true
;
console.log
('页面触发返回按钮', Vue.isBack
)
}
3. 页面进入设置 isBack 为false
// router/index.js
router.beforeEach
((to, from, next
) => {
Vue.isBack
=false
;
next
();
})
4. 全局混入 beforeRouteLeave 页面离开之前清除当前页面缓存
// main.js
Vue.mixin
({
beforeRouteLeave: function
(to, from, next
) {
let tabbars
= ['/home',
'/cloudClassroom',
'/customService',
'/my']
if
(Vue.isBack
&& !tabbars.includes
(from.fullPath
)) { // 判断是返回上一页 并且不是底部按钮
let vnode
= this.
$vnode
var key
= vnode.key
== null ? vnode.componentOptions.Ctor.cid +
(vnode.componentOptions.tag ?
`::${vnode.componentOptions.tag}` : "") : vnode.key
;
let cache
= vnode.parent.componentInstance.cache
let keys
= vnode.parent.componentInstance.keys
var index
= keys.indexOf
(key
);
if (cache
[key
]) {
if (keys.length
) {
var index
= keys.indexOf
(key
);
if (index
> -1
) {
keys.splice
(index, 1
);
}
}
delete cache
[key
];
}
}
next
()
}
})