uniapp 开发微信小程序,怎么在用户离开页面之前 增加一个确认提示框,只有确认了才退出
时间: 2024-09-25 19:15:22 浏览: 134
在 UniApp 开发微信小程序中,为了在用户离开页面前增加确认提示框,你可以利用微信小程序提供的生命周期钩子函数 `onHide()` 和自定义弹窗组件。当用户尝试离开页面时,`onHide()` 函数会被调用。在这个函数里,你可以创建一个弹窗,并处理用户的确认操作。
以下是简单的步骤:
1. 首先,在需要添加确认提示的页面文件中,例如 `index.vue` 中,监听 `onHide` 事件:
```html
<template>
<view>
<!-- 页面内容... -->
<button @tap="handleClose">关闭页面</button>
</view>
</template>
<script>
export default {
methods: {
handleClose() {
this.showConfirmModal();
},
},
onHide() {
// 用户点击关闭按钮或直接切换到其他页面
this.showConfirmModal();
},
data() {
return {
confirmModalVisible: false, // 存储弹窗是否可见的状态
};
},
components: {
ConfirmModal, // 自定义的确认弹窗组件
},
};
</script>
```
2. 创建一个名为 `ConfirmModal` 的自定义组件,比如 `confirm-modal.vue`:
```html
<template>
<view v-if="confirmModalVisible" modal bindclose="cancel">
<view slot="title">确认离开页面?</view>
<view slot="content">确定要退出吗?</view>
<button type="primary" block round @click="confirm">确认</button>
<button type="default" block round @click="cancel">取消</button>
</view>
</template>
<script>
export default {
props: {
confirmModalVisible: { type: Boolean, default: false },
},
methods: {
confirm() {
// 确认操作,如保存数据或提交事务等
this.$emit('close'); // 关闭弹窗并允许页面隐藏
},
cancel() {
this.confirmModalVisible = false; // 取消操作,保留当前页面
},
},
onShow() {
// 弹窗显示时,阻止默认的关闭行为
this.$once('touchstart', function(e) {
e.stopPropagation();
});
},
onClose() {
// 弹窗关闭后,执行实际的离开逻辑
// 这里可以更新 confirmModalVisible 或者调用 onHide 处理
},
};
</script>
```
3. 当你在 `handleClose` 或 `onHide` 中调用 `this.showConfirmModal()` 时,弹窗会显示出来。用户点击“确认”将关闭弹窗并允许页面关闭,点击“取消”则保持当前页面。
记得在项目结构中正确引入这两个组件,并且根据实际需求调整相关的业务逻辑。
阅读全文