vue-router beforeRouteLeave 引发的问题

  1. 问题:
    用户需求是当用户在创建商品时,点击了左侧菜单,做一个离开提醒‘是否确定离开?’。
    如下实现:
    但是,出现一个问题:用户点击左上角浏览器回退按钮时,这个弹出提醒就会闪现,立马消失。请教大神们~~

      beforeRouteLeave(to, from, next) {
              console.log(' beforeRouteLeave !', this)
               if (this.isSubmit=='1' || this.saveLoading == true || this.cancleFlag ==true || this.previewFlag == true) { //去除这三种情况 不用离开提醒
                      next()
              } else {
                      this.$confirm('确定离开?请保存数据!', '提示', {
                              confirmButtonText: '确定',
                              cancelButtonText: '取消',
                              type: 'warning'
                              }).then(() => {
                                  next()
                              }).catch(() => {
                                  next(false)    
                      });
            }   
       },
阅读 6k
4 个回答

解决方案

setTimeout(() => { // 此处必须要加延迟执行,主要解决浏览器前进后退带来的闪现
    this.$confirm('您的数据尚未保存,是否离开?', '离开页面', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      next()
    }).catch(() => {
      next(false)
    })
  }, 200)
新手上路,请多包涵
beforeRouteLeave(to, from, next) {
  next(false)
  setTimeout(() => {
    this.$confirm('是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
 }).then(() => {
      this.$router.go(-1)
      next(false)
    }).catch(() => {
      next()
    })
  }, 100)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进