手指在屏幕上产生了移动:
- 手指按下屏幕事件 touchstart;
- 手指离开屏幕事件 touchend;
- 手指在屏幕上的坐标 event.changedTouches[0].clientX 和 clientY
- clientX:X轴方向(左右)
- clientY:Y轴方向(上下)
根据坐标判断滑动的位置
代码示例
1,在pages 同级页面下新建 components 文件夹,新建 swiperPosition.vue 组件
定义两个触发事件
<template>
<view @touchstart="touchStart" @touchend="touchEnd">
<slot></slot>
</view>
</template>
<script>
export default {
data() {
return {
// 刚触碰的时间
startTime: 0,
// 刚触碰的位置
startPosition: 0,
// 结束的位置
endPosition: 0
}
},
methods: {
touchStart(event) {
// 获取初始时间
this.startTime = Date.now()
// 获取初始的位置
this.startPosition = event.changedTouches[0].clientX
},
touchEnd(event) {
const endTime = Date.now()
// 如果手指滑动的时间超过3s 就默认不合法
if (endTime - this.startTime > 3000) {
return;
}
if (Math.abs(this.endPosition - this.startPosition) > 10) {
this.endPosition = event.changedTouches[0].clientX
var elePosition = this.endPosition - this.startPosition > 0 ? "right" : "left"
} else {
return;
}
// console.log(elePosition)
// 在此处需要将数据传递过去,使用子组件给父组件传值的方式
this.$emit('positionData', elePosition)
},
}
}
</script>
2,在需要的组件页面中引入,并且监听属性的值
<template>
<view>
<swiperPosition @positionData="getPositionData">
触摸滑动
</swiperPosition>
</view>
</template>
<script>
//组件绝对路径
import swiperPosition from '@/components/swiperPosition.vue'
export default {
data() {
return {
}
},
components: {
swiperPosition
},
methods: {
getPositionData(e) {
// 获取传递过来的参数值
console.log(e)
}
}
}
</script>
<style scoped lang="scss">
</style>