vue拦截阻止浏览器后退事件以及添加页面跳转前的确认对话

10次阅读

共计 970 个字符,预计需要花费 3 分钟才能阅读完成。

需求是这样的:用户在编辑页以及新增页面时,如果用户手动要跳转到其它页面,就出来一个弹窗提示用户巴拉巴拉。。。

然后,使用 vue 的 beforeRouteLeave 路由守卫可以对一些路由操作进行跳转前提示,但是如果用户点了浏览器的后退按钮,那这个路由守卫基本没用了啊,那个弹窗就闪了一下就消失了,路由直接改变,但是页面不刷新(写这篇文章时,我在想,可能我的路由有问题,不然为什么路由变了,但是页面不刷新?)

下面是代码,在 App.vue 里面添加:

mounted () {if (window.history && window.history.pushState) {history.pushState(null, null, document.URL)
      window.addEventListener('popstate', this.goBack, false)
    }
  },
  destroyed () {window.removeEventListener('popstate', this.goBack, false)
  },
  methods: {goBack () {
      // 该事件仅在浏览器后退按钮被点击时触发
      let needCofirmRouter = ['/addPro']
      console.log(document.URL.split('#')[1])
      history.pushState(null, null, null)
      if (needCofirmRouter.indexOf(document.URL.split('#')[1]) > -1) {
        this.$confirm('请确认数据已保存,页面跳转后已填写的数据会被清空,是否继续跳转?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          // 这里不可以使用 back,go(-1)等方法,不然会再次触发该事件进入死循环
          // this.$router.go(-1)
        }).catch((ms) => {})
      }
    }
  }

在 App.vue 里面添加:
对 $route 进行 wacth 监听

watch: {$route (to, from) {this.lastRouter = from.path}
  },

然后对 to 和 form 的 path 进行判断,如果是需要弹出退出确认的页面,就进行弹窗提示

正文完
 0