vue导航守卫beforeRouteLeave浏览器返回时,自定义弹窗提醒用户保存信息

10 篇文章 4 订阅

H5页面中经常会遇到的情况,当前页面点击返回,想要提示弹窗"是否确认离开当前页面"之类的需求。自己试着看了一下网上的方法,大多是alert出系统弹窗。其实要实现自定义弹窗提示,也是很容易的。

从另一个页面点击跳转到当前页(如下),点击浏览器返回按钮,则会弹窗下面的弹窗,点击弹窗确定按钮,页面返回上一页

 

完整代码:

<template>
	<div class="templ">
		<div>123</div>
		
	    <div class="deleteTip pubsontext" v-show="tipshow">
	      <div class="tipSon">
	        <p>确定要退出当前页?</p>
	        <div class="footerBut">
	          <span class="cancle" @click="tipColse">取消</span>
	          <span class="sure" @click="tipBacks">确定</span>
	        </div>
	      </div>
	    </div>
  	</div>
</template>

<script>
	export default {
	    data() {
	      return {
			tipshow:false,//控制提示弹窗显隐
			backStatu: false,//判断当执行页面回退时是否要执行next(true);
	      };
	    },
	    //监听当前页面返回事件
	    beforeRouteLeave(to, from, next) {
	    	//next方法传true或者不传为默认历史返回,传false为不执行历史回退
			if(this.backStatu){
				next(true);
			}else{
				next(false);
			}
			this.tipshow = true;
	    },
	    methods: {
			tipColse() {//控制提示弹窗显隐
				this.tipshow = !this.tipshow;
			},
			tipBacks() {
				this.backStatu = true;
				this.$router.go(-1);
			},
	    }
	}
</script>

<style>
.deleteTip {
    height: 100%;
    width: 100%;
    position: fixed;
    background: rgba(0, 0, 0, 0.5);
    top: 0;
    z-index: 4;
}
.pubsontext .tipSon {
    top: 30%;
}
.deleteTip .tipSon {
    text-align: center;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: auto 0;
    background: #fff;
    border-radius: 0.2rem;
    padding: 1rem 0.4rem 0.5rem;
}
.pubsontext .tipSon p {
    text-align: center;
    font-size: 0.3rem;
}
.deleteTip .tipSon p {
    color: #000000;
    line-height: 0.42rem;
    padding-bottom: 0.5rem;
}
.deleteTip .tipSon .footerBut {
    display: flex;
    line-height: 0.7rem;
    font-size: 0.36rem;
    color: #666;
}
.deleteTip .tipSon .footerBut .cancle {
    background: #4293e5;
    color: #fff;
    margin-right: 0.1rem;
}
.deleteTip .tipSon .footerBut .sure {
    color: #4293e5;
    margin-left: 0.1rem;
}
.deleteTip .tipSon .footerBut .cancle, .deleteTip .tipSon .footerBut .sure {
    flex: 1;
    font-size: 0.36rem;
    border: 0.01rem solid #4293e5;
    border-radius: 0.5rem;
}
</style>

需注意,若页面内有其他点击回退事件时,要留意是否会跟beforeRouteLeave事件冲突

觉得有用的点下赞,让我了解一下是否帮到了你们

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caicaicai404

对作者使用钞能力,欢迎点这里

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值