0

    Vue监听浏览器原生返回按钮,进行路由转跳操作

    2023.05.23 | admin | 146次围观

    今天测试给我报了个bug说点击浏览器返回页数据显示的不对,我查了半天原因:需要监听浏览器的回退按钮浏览器回退按钮事件,并阻止其默认事件。

    具体操作方法如下:

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

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

    Vue监听浏览器原生返回按钮,进行路由转跳操作

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

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

    3、将监听操作写在methods里面,removeEventListener取消监听内容必须跟开启监听保持一致浏览器回退按钮事件,所以函数拿到methods里面写

    cancel: function() {
          if(this.orderId){
              this.$router.push({
                name:"orderList",
                params: {id:this.orderId},
                    });
          }else{
          this.$router.go(-1);
          }
        },

    版权声明

    本文仅代表作者观点。
    本文系作者授权发表,未经许可,不得转载。

    标签: 路由vue
    发表评论