当前位置:首页 > 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 属性。

<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 简化手势识别。

安装 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)。

touchmove实现左右滑动vue

标签: touchmovevue
分享给朋友:

相关文章

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式…

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-se…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现动态

vue实现动态

Vue 实现动态路由的方法 在 Vue 中实现动态路由通常涉及以下几个关键步骤: 使用 Vue Router 的动态路由匹配 通过 Vue Router 的 :param 语法可以实现动态路由匹配…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…