微信小程序,uniapp,监听物理返回键并阻止返回

676 阅读1分钟

请不要让page-container占位,page-container是个弹出框,点击物理返回键会关闭弹框

<page-container :show="myData.showView" overlay="{{false}}" custom-style="height:0;overflow:scroll"
			@beforeleave="onBeforeLeave">
</page-container>

此时我们可以进行一些操作,比如点击返回按钮时回到首页而不是直接退出

<script setup>
	let myData = reactive({
		showView: true,
	})
	// 离开页面前触发
	let onBeforeLeave = (res) => {
		// 获取页面栈
		const pages = getCurrentPages();
		// console.log(145, pages);
		const currentPage = pages[pages.length - 1].route;

		// 判断是否为首页
		if (currentPage !== 'pages/index/index') {
			// 如果不是首页,点击返回按钮时跳转到首页
			// 跳转到首页
			myData.showView = true
			uni.reLaunch({
				url: '/pages/index/index', // 请替换成你首页的路径
			});
		}
		myData.showView = true
	}
</script>