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

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

然后,使用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进行判断,如果是需要弹出退出确认的页面,就进行弹窗提示

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理