uniApp App内嵌H5打开内部链接,左滑右滑页面会直接关闭H5项目,退出应用,而不是我想要的返回上一级页面。
处理方法如下图:
App.vue具体代码:
javascript
<template>
<div id="app" data-theme="default">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</div>
</template>
<script>
import Vue from 'vue'
export default {
data() {
return {
}
},
created() {
// 监听网络状态变化
window.addEventListener('online', this.handleOnline)
window.addEventListener('offline', this.handleOffline)
// 监听页面加载错误
window.addEventListener('error', this.handlePageError)
},
mounted() {
window.onerror = (message, source, lineno, colno, error) => {
if (error && error.stack) {
console.log(error, 'error')
this.$toast('网络异常,请检查网络连接')
}
return true
}
// document.documentElement.style.setProperty(
// '--statusbar-height',
// '30px'
// )
window.getBarStatusHeightCallback = res => {
Vue.prototype.$barHeight = res
console.log('状态栏高度', res)
document.documentElement.style.setProperty(
'--statusbar-height',
`${res}px`
)
}
// 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
document.addEventListener('UniAppJSBridgeReady', () => {
uni.webView.getEnv(res => {
console.log('当前环境:' + JSON.stringify(res), uni)
Vue.prototype.$Env = res
})
uni.postMessage({
data: {
type: 'getBarHeight',
msg: '获取状态栏高度'
}
})
})
// 滑动返回
let startX = 0
document.addEventListener('touchstart', e => {
startX = e.touches[0].clientX
})
document.addEventListener('touchmove', e => {
e.preventDefault() // 阻止默认返回行为
const per = document.body.clientWidth / 5 // 页面宽度分成5份
if (startX < per || startX > per * 4) { // 控制开始触碰点在小于页面的五分之一或者大于页面的五分之四氛围内有效
const deltaX = e.touches[0].clientX - startX
if (Math.abs(deltaX) > 50) { // 左滑、右滑,阈值50px
this.$router.goBack()
// if (!['/home', '/my'].includes(this.$route.matched[0].path)) {
// this.$router.goBack()
// }
}
}
})
},
beforeDestroy() {
// 移除事件监听,避免内存泄露
window.removeEventListener('online', this.handleOnline)
window.removeEventListener('offline', this.handleOffline)
window.removeEventListener('error', this.handlePageError)
},
methods: {
handleOnline() {
console.log('网络连接恢复')
// 处理逻辑,例如提示用户或重试操作
},
handleOffline() {
console.log('网络连接断开')
this.$toast('网络异常,请检查网络连接')
// 处理逻辑,例如提示用户网络不给力
},
handlePageError(event) {
console.error('页面加载出错', event.target.src)
this.$toast('网络异常,请检查网络连接')
// 处理逻辑,例如提示用户或重定向到错误页面
}
}
}
</script>
<style lang="scss" scoped>
:root {
--statusbar-height: 0; //状态栏高度
--primary-color: #24a854;
}
#app {
height: 100%;
// overflow: auto;
* {
touch-action: pan-y;
}
}
::v-deep(.van-button--block) {
border-radius: 14px;
}
</style>