h5开发后退拦截,刷新或者跳转后后退不会多次拦截

在移动端开发中,经常有一些编辑页面要防止用户手势后退,这边用到vue和vant

mounted() {
     // 添加返回监听
     window.addEventListener("popstate", this.onBack)
 },
 data () {
 	return {
		mixinPath: "",
		mixinRemove: false // 如果路由跳转用replace代替,那么需要移除一下
	}
 },
 methods: {
 	onBack () {
        Dialog.confirm({
            title: "退出",
            message: "退出将不保存此步骤数据"
        }).then(() => {
                this.$router.go(-1);
                sessionStorage.removeItem(this.mixinPath);
          }).catch(() => {
              history.pushState(null, null, document.URL);
          })
    },
    // 防止刷新或者后退多次记录history
    haveHistory (path) {
           this.mixinPath = path
           if (!sessionStorage.getItem(path)) {
               history.pushState(null, null, document.URL);
               sessionStorage.setItem(path, 1)
           }
       }
 },
 beforeRouteEnter (to, from, next) {
      next((vm) => {
            console.log(to)
            // 防止刷新时多push
            vm.haveHistory(to.path);
        })
   },
 // 退出组件后取消监听
 beforeDestroy () {
 		if (this.mixinRemove) {
            sessionStorage.removeItem(this.mixinPath)
        }
      window.removeEventListener("popstate", this.onBack, false)
 },

2022-08-09 修改
有更简单的方式,记得稍微延迟一下

beforeRouteLeave(to, form, next) {
   setTimeout(() => {
       this.$dialog
          .confirm({
              title: "是否确认退出",
              message: "是否确认退出?",
          })
          .then(() => {
              next();
          })
          .catch(() => {
              next(false); // false这个参数记得填写,拦截后退作用
          });
   }, 200);
},

版权声明:本文为qq_28353055原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。