要分清两者的区别。
首先是监听页面的刷新与离开,此时相当于直接在这个网页中按了刷新,如果是webapp则是离开这个app而不是切换路由!
如果是用js的特性监测,则是不仅可以页面的刷新与离开,还能切换路由。注意当keepalive时即使切换了路由也无效。
在script中直接增加监听器监视beforeunload:
//监视如果页面离开
created() {
window.addEventListener('beforeunload', this.updateHandler)
},
beforeDestroy() {
this.finalItemDetail(); // 自己要进行的操作
},
destroyed() {
window.removeEventListener('beforeunload', this.updateHandler)
},
然后methods中添加finalItemDetail和updateHandler方法:
updateHandler() {
this.finalItemDetail()
},
finalItemDetail() {
console.log('刷新或关闭');
},
如果想监听某个特定的页面的离开,比如我现在在/index下,现在去了/index/001下面,就可以在watch中监听路由的变化,前提是实用vue-router。
如果是简单的判断路由变化可以用注释掉的,直接执行clear方法(自己定义在methods中)
但是注意这个只能监听自己子路由的变化!
watch: {
// 如果路由有变化,会再次执行clear方法
// "$route": "clear",
$route(to , from){
console.log( to.path, from.path );
this.clear(to.path);
}
},
然后我还额外做了个判断:
clear(path) {
if(path!="/item/item01/evaluate")
console.log("从这个页面离开了");
this. active=0;
},