This project is developed for uniapp, native applets can also refer to these two methods.
wx.enableAlertBeforeUnload
statement in onLoad
wx.enableAlertBeforeUnload({
message: '请您填写数据',
success:()=>{}
})
Advantages: simple and convenient
Disadvantages: Unable to customize styles, button text and styles
page-container
This is a component similar to a pop-up box. You can check the specific parameters on the official website.
Return operations include: top navigation, right swipe gesture, Android physical return key and call navigateBack interface
Pros: You can customize the return box
<template>
<view>
<text>测试阻止返回的页面</text>
<!-- 阻止返回 -->
//注意一定要用v-if 才可以,不然即使showPage1设置为false,第二次也会直接返回
<view class="" v-if="showPage1">
<page-container :show="showPage1" :overlay="false" @beforeleave="beforeleave('showPage1')"></page-container>
</view>
</view>
</template>
//数据及方法
data(){
return {
showPage1: true //一开始设置为显示
}
},
methods: {
beforeleave(){
this.showPage1 = false //这个很重要,一定要先把弹框删除掉
uni.showModal({
title: `确定要退出吗`,
success: (e)=>{
if(e.confirm) {
//判断是上一个页面进入(返回),还是直接进入这个页面(回首页)
let pages = getCurrentPages()
if(pages.length == 1){
uni.switchTab({
url: '/pages/index/index'
})
}else {
uni.navigateBack(1)
}
}else {
//点取消,生成新的弹框
this.showPage1 = true
}
},
})
}
}