uniapp实现左右滑动切换页面
时间: 2023-08-24 17:09:45 浏览: 78
要实现左右滑动切换页面,可以使用uni-app提供的swiper组件,具体步骤如下:
1. 在页面中添加swiper组件:
```html
<swiper :current="current" @change="swiperChange" :duration="500">
<swiper-item>
<!-- 第1个页面内容 -->
</swiper-item>
<swiper-item>
<!-- 第2个页面内容 -->
</swiper-item>
<swiper-item>
<!-- 第3个页面内容 -->
</swiper-item>
</swiper>
```
2. 在data中定义current变量,默认值为0表示当前显示第1个页面:
```js
data() {
return {
current: 0
}
}
```
3. 在methods中添加swiperChange方法,监听swiper组件的change事件,更新current变量的值:
```js
methods: {
swiperChange(event) {
this.current = event.detail.current;
}
}
```
4. 在样式中设置swiper的宽度和高度,以及swiper-item的宽度和高度为100%:
```css
swiper {
width: 100%;
height: 100%;
}
swiper-item {
width: 100%;
height: 100%;
}
```
5. 最后,使用touch事件监听用户的滑动操作,根据滑动的方向更新current变量的值,实现页面切换:
```js
methods: {
// 左右滑动切换页面
touchstart(event) {
this.touchStartX = event.touches[0].pageX;
},
touchend(event) {
this.touchEndX = event.changedTouches[0].pageX;
if (this.touchEndX - this.touchStartX > 50 && this.current > 0) {
this.current--;
} else if (this.touchEndX - this.touchStartX < -50 && this.current < 2) {
this.current++;
}
}
}
```
完整代码如下:
```html
<template>
<swiper :current="current" @change="swiperChange" :duration="500">
<swiper-item>
<!-- 第1个页面内容 -->
</swiper-item>
<swiper-item>
<!-- 第2个页面内容 -->
</swiper-item>
<swiper-item>
<!-- 第3个页面内容 -->
</swiper-item>
</swiper>
</template>
<script>
export default {
data() {
return {
current: 0,
touchStartX: 0,
touchEndX: 0
}
},
methods: {
swiperChange(event) {
this.current = event.detail.current;
},
touchstart(event) {
this.touchStartX = event.touches[0].pageX;
},
touchend(event) {
this.touchEndX = event.changedTouches[0].pageX;
if (this.touchEndX - this.touchStartX > 50 && this.current > 0) {
this.current--;
} else if (this.touchEndX - this.touchStartX < -50 && this.current < 2) {
this.current++;
}
}
}
}
</script>
<style>
swiper {
width: 100%;
height: 100%;
}
swiper-item {
width: 100%;
height: 100%;
}
</style>
```