一,手指滑动操作的原理
手指在屏幕上产生了移动:
- 手指按下屏幕事件 touchstart;
- 手指离开屏幕事件 touchend;
- 手指在屏幕上的坐标 event.changedTouches[0].clientX 和 clientY
手指在屏幕上的时间不能太长
- 记录下手指按下的时间 Date.now()
- 记录下手指离开的时间 Date.now()
- 在手指离开的时候做减法运算,求时间差
根据坐标判断滑动的位置
代码示例
1,定义两个触发事件
<view class="touch"
@touchstart="touchStart"
@touchend="touchEnd"
></view>
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()
if (endTime - this.startTime > 2000){
// 如果手指滑动的距离超过2s 就默认不合法
return;
}
// 判断其滑动的距离是否值得触发,给定一个10 的距离
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)
},
}
}
二,实现代码的封装–组件
- 实现插槽slot 功能
- 像外部(例如:父组件)传递滑动的方向
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()
if (endTime - this.startTime > 2000){
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,在需要改组件的页面中引入,并且监听属性的值
<swiper-postino @positionData="getPositionData">
......
</swiper-postino>
import swiperPosition from '@/components/swiperPosition'
export default {
components: {swiperPosition},
methods: {
getPositionData(e){
// 获取传递过来的参数值
console.log(e)
}
}
}