vue的钩子函数beforeDestroy()、destroy() 只是在页面切换的时候触发,并不能监听F5或者网页关闭时的事件。
js种beforeunload事件可以在当前页面刷新或者关闭时调用。
使用:
methods:{
// beforeunload对用的方法
beforeunloadFn(e) {
if(this.socket) {
this.socket.close();
clearInterval(this.heartBeatInterval);
this.heartBeatInterval = null;
}
}
},
mounted() {
// 初始化socket
this.init();
// 给beforeunload添加事件,并监听beforeunload
window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
},
beforeDestroy () {
// 当页面切换时关闭监听
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
}