vue监听浏览器

版权声明:未经本人同意不得转载 一切法律责任 后果自负 https://blog.csdn.net/xy19950125/article/details/88874006

需求: 在浏览器打开一个页面当返回或关闭的时候  弹出提示框 

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

mounted(){
  if (window.history && window.history.pushState) {
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', this.returns, false);
  }
},

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

destroyed(){
  window.removeEventListener('popstate', this.returns, false);
},

3、监听操作,removeEventListener取消监听内容必须跟开启监听保持一致

methods:{

     returns(){

          alert('确定退出?')

          //this.$router.replace({path: '/'});

         //replace替换原路由,作用是避免回退死循环

扫描二维码关注公众号,回复: 6640733 查看本文章

     }

}

猜你喜欢

转载自blog.csdn.net/xy19950125/article/details/88874006