uni自定义onBackPress事件

onBackPress 函数 return 非 true 以外的值都会执行默认的返回行为,只有 return true 才不会执行返回事件,所以在执行自定义事件时一定要返回 true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script>
export default {
data() {
return {
isConfirm: false //处理返回逻辑
};
},
methods: {
onBackPress() {
if (this.isConfirm == false) {
uni.showModal({
content: "数据尚未保存,你确定要返回吗?",
success: (res) => {
// 一定要保证this的指向问题,否则会导致无限的弹出modal,可以考虑用that保存this指针或是使用箭头函数
if (res.confirm) {
this.isConfirm = true;
//navigateBack会再次执行onBackPress事件,所以在进入函数的时候我们加了isConfirm来判断是否执行自定义的事件
uni.navigateBack();
}
}
});
return true;
} else {
return false;
}
}
}
};
</script>