vue導航守衛beforeRouteLeave瀏覽器返回時,自定義彈窗提醒用戶保存信息

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章