uni-app监听页面滑动手势实现页面左右滑动,tab自动切换

页面结构:

页面有3个tab,对应的id为1,2,3

父组件中:

<view>
  <listVue :conditions="conditions" ref="listRef" :activeTab="activeTab" @change="handleChange"></listVue>
</view>

子组件中:

<view class="list" ref="listComRef" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
  <mescroll-uni ref="mescrollRef" top="660" bottom="40" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption" :down="upOption">
	...
  </mescroll-uni>
</view>

代码实现:

思路:记录滑动开始位置和结束位置,滑动结束子组件使用this.$emit告诉父组件向左还是向右活动,在父组件中设置当前选中的Tab以及后续数据请求操作。滑动到最左边时继续向右滑不切换tab,对应滑到最右边继续向左滑动不切换tab。

子组件中:

touchStartX: 0, // 记录滑动开始的位置
touchEndX: 0 // 记录滑动结束的位置

touchStart(e) {
  const x = e.touches[0].pageX;
  // console.log('滑动开始',x);
  this.touchStartX = x;
},
touchMove(e) {
  const x = e.touches[0].pageX;
  // console.log('滑动中',x);
  this.touchEndX = x;
},
touchEnd(e) {
  // console.log('滑动结束', e);
  const { touchStartX, touchEndX } = this;
  if (touchStartX < touchEndX - 50) {
	// 向右滑动了
	// console.log(1111, '向右');
	this.$emit('change', 'right');
  }
  if (touchStartX > touchEndX + 50) {
	// 向左滑动了
	// console.log(2222, '向左');
	this.$emit('change', 'left');
  }
},

父组件中:

handleChange(data) {
  this.activeTab = data === 'right' ? (this.activeTab > 1 ? this.activeTab - 1 : this.activeTab) : this.activeTab < 3 ? this.activeTab + 1 : this.activeTab;
},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值