<template>
<div class="touch-back-page">
<div class="left-side" @touchstart.stop="handleTouchStart" @touchend.stop="handleTouchEnd" v-if="leftDrag"></div>
<div class="right-side" @touchstart.stop="handleTouchStart" @touchend.stop="handleTouchEnd" v-if="rightDrag"></div>
</div>
</template>
<script>
export default {
name: 'touchBack',
data() {
return {
startPosX: 0, // 触碰开始位置
direction: 'left', // 滑动方向
windowWidth: document.body.offsetWidth, // 屏幕宽度
};
},
props: {
// 左侧滑动
leftDrag: {
type: Boolean,
default: true,
},
// 右侧滑动
rightDrag: {
type: Boolean,
default: false,
},
},
methods: {
// 触碰开始
handleTouchStart(e) {
if (!e.touches) {
return;
}
this.startPosX = e.touches[0].clientX;
this.direction = this.startPosX > this.windowWidth / 2 ? 'right' : 'left';
},
// 触碰结束
handleTouchEnd(e) {
if (!e.changedTouches || !e.changedTouches[0]) {
return;
}
let x = e.changedTouches[0].clientX;
const offset = x - this.startPosX;
const canDrag = (this.direction === 'left' && offset >= 50) || (this.direction === 'right' && offset <= -50);
if (canDrag) {
this.startPosX = 0;
this.$emit('goBack');
}
},
},
};
</script>
<style scoped lang="less">
.touch-back-page {
> div {
position: fixed;
top: 0;
bottom: 0;
width: 30px;
opacity: 0.01;
z-index: 10000;
}
.left-side {
left: 0;
}
.right-side {
right: 0;
}
}
</style>
注意:
由于是页面的左右两侧开启了30px的宽度用来作为用户左右滑的事件触发层,因此在这个位置的点击或者其他事件会失效。