vue3项目在页面退出时弹窗确认--用vant组件Dialog弹窗在路由改变的时候不生效问题

写vue3的H5项目的时候有个需求是回退时弹窗确认是否退出当前页面

一、第一个办法------使用onbeforeRouteLeave路由钩子

 const formRouteAbi = localStorage.getItem("formRouteAbi"); //获取上一页路径
    onBeforeRouteLeave((to, from, next) => {
      if (formRouteAbi == to.fullPath && topicInfo.topicNow > 0) {
      
        Dialog.confirm({
            closeOnPopstate: false,//不加这个弹窗不会展示的,因为路由发生了变化
          message: `你确定要退出社交能力测试吗,再测试${
            topicInfo.topicNum - topicInfo.topicNow
          }个题就完成该能力测试了。`,
          confirmButtonText: "继续测试",
          cancelButtonText: "确认退出",
        })
          .then(() => {
            next(false);
          })
          .catch(() => {
            next(true);
          });
      } else {
        next(true);
      }
    });

二、第二个办法------使用history.pushState(null, "null", document.URL);禁用前进后退功能

禁用回退功能,手动添加跳转事件

onMounted(() => {
      history.pushState(null, "null", document.URL);
      window.addEventListener("popstate", handleEvent, false);
    });
    onUnmounted(() => {
      window.removeEventListener("popstate", handleEvent, false);
    });
    const url =
      process.env.NODE_ENV == "production"
        ? location.origin + "/shengchan"
        : location.origin;
    const handleEvent = () => {
      history.pushState(null, "null", document.URL);
      if (topicInfo.topicNow > 0) {
        Dialog.confirm({
        closeOnPopstate: false,
        message: `你确定要退出社交能力测试吗,再测试${
          topicInfo.topicNum - topicInfo.topicNow
        }个题就完成该能力测试了。`,
        confirmButtonText: "继续测试",
        cancelButtonText: "确认退出",
      })
        .then(() => {})
        .catch(() => {
          location.href = `${url}${formRouteAbi}`;
        });
      } else {
        location.href = `${url}${formRouteAbi}`;
      }
    };
两种方法,都可以实现
posted @ 2022-09-02 16:27  挥不去的执念  阅读(2184)  评论(0编辑  收藏  举报