要分清兩者的區別。
首先是監聽頁面的刷新與離開,此時相當於直接在這個網頁中按了刷新,如果是webapp則是離開這個app而不是切換路由!
在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;
},