vue项目中h5页面监听手机物理返回键

1,951 阅读1分钟

监听手机返回键操作

一、挂载完成后,判断浏览器是否支持popstate,监听popstate

if (window.history && window.history.pushState) {
    //history.pushState(null, null, `#${this.$route.fullPath}`);
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', this.watchReturn, false);//false阻止默认事件
  }

2、页面销毁时,取消监听。否则其他vue路由页面也会被监听

destroyed() {
	window.removeEventListener('popstate', this.watchReturn, false);//false阻止默认事件
},

3、将监听操作写在methods里面,removeEventListener取消监听内容必须跟开启监听保持一致,所以函数拿到methods里面写

methods:{
  watchReturn(){
    console.log("监听到了");
  }
}

参考:blog.csdn.net/so12138/art…