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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caimingxian401/article/details/83107442

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事件冲突

猜你喜欢

转载自blog.csdn.net/caimingxian401/article/details/83107442