当前位置:首页 > VUE

touchmove实现左右滑动vue

2026-02-20 21:23:09VUE

实现左右滑动的 Vue 方法

使用 touchmove 事件监听

在 Vue 中监听 touchstarttouchmovetouchend 事件,通过计算触摸点的位移差实现左右滑动判断。

<template>
  <div 
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    style="width: 100%; height: 200px; background: #eee;"
  >
    {{ swipeDirection }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      startX: 0,
      endX: 0,
      swipeDirection: ''
    };
  },
  methods: {
    handleTouchStart(e) {
      this.startX = e.touches[0].clientX;
    },
    handleTouchMove(e) {
      this.endX = e.touches[0].clientX;
    },
    handleTouchEnd() {
      const diff = this.endX - this.startX;
      if (Math.abs(diff) > 50) { // 阈值设为50px
        this.swipeDirection = diff > 0 ? '右滑' : '左滑';
      }
    }
  }
};
</script>

结合 CSS 过渡效果

为滑动添加平滑动画效果,通过动态绑定 transform 属性。

touchmove实现左右滑动vue

<template>
  <div 
    @touchstart="startDrag"
    @touchmove="onDrag"
    @touchend="endDrag"
    :style="{ transform: `translateX(${offsetX}px)` }"
    style="transition: transform 0.3s; width: 100%; height: 200px;"
  >
    滑动内容
  </div>
</template>

<script>
export default {
  data() {
    return {
      startX: 0,
      offsetX: 0,
      isDragging: false
    };
  },
  methods: {
    startDrag(e) {
      this.startX = e.touches[0].clientX;
      this.isDragging = true;
    },
    onDrag(e) {
      if (!this.isDragging) return;
      this.offsetX = e.touches[0].clientX - this.startX;
    },
    endDrag() {
      this.isDragging = false;
      // 根据滑动距离决定最终位置(如归零或切换到下一页)
      this.offsetX = 0;
    }
  }
};
</script>

使用第三方库

集成 vue-touchhammer.js 简化手势识别。

touchmove实现左右滑动vue

安装 hammer.js

npm install hammerjs

示例代码:

import Hammer from 'hammerjs';

export default {
  mounted() {
    const hammer = new Hammer(this.$el);
    hammer.on('swipeleft', () => {
      console.log('左滑触发');
    });
    hammer.on('swiperight', () => {
      console.log('右滑触发');
    });
  }
};

注意事项

  1. 性能优化:避免在 touchmove 中执行复杂计算,必要时使用 requestAnimationFrame
  2. 边界处理:限制滑动范围,防止内容滑出可视区域。
  3. 移动端适配:添加 touch-action: pan-y CSS 属性防止默认滚动行为干扰。
  4. 阈值判断:根据实际需求调整滑动距离阈值(如示例中的50px)。

标签: touchmovevue
分享给朋友:

相关文章

vue实现过滤

vue实现过滤

Vue实现过滤的方法 在Vue中实现数据过滤可以通过多种方式完成,以下是几种常见的方法: 使用计算属性过滤 计算属性是Vue中处理数据过滤的理想选择,它们基于响应式依赖进行缓存,只有在相关依赖发生改…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutati…

jquery实现vue

jquery实现vue

jQuery 和 Vue.js 是两种不同理念的前端工具,jQuery 以 DOM 操作和事件驱动为核心,而 Vue.js 是数据驱动的现代化框架。如果想用 jQuery 实现类似 Vue 的功能(如…

vue实现选择

vue实现选择

Vue 实现选择功能的方法 在 Vue 中实现选择功能可以通过多种方式完成,以下介绍几种常见的实现方法。 使用 v-model 绑定单选 通过 v-model 可以轻松实现单选功能。以下是一个简单的…

vue实现登录退出

vue实现登录退出

实现登录功能 在Vue中实现登录功能通常需要结合表单验证、API请求和状态管理。以下是一个基础实现示例: 安装必要依赖(如axios和vuex): npm install axios vuex 创…

vue实现cs程序

vue实现cs程序

Vue 实现 CS(客户端-服务器)程序 Vue 本身是一个前端框架,主要用于构建用户界面。要实现一个完整的 CS(客户端-服务器)程序,需要结合后端技术。以下是实现的基本思路和步骤: 前端部分(V…