当前位置:首页 > VUE

vue横向滑动实现

2026-01-17 20:37:44VUE

Vue 横向滑动实现方法

使用 CSS Flexbox 布局

在容器元素上设置 display: flexoverflow-x: auto,子元素设置 flex-shrink: 0 防止被压缩。

<div class="scroll-container">
  <div v-for="item in items" :key="item.id" class="scroll-item">
    {{ item.content }}
  </div>
</div>
.scroll-container {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
}

.scroll-item {
  flex-shrink: 0;
  width: 200px; /* 固定宽度 */
  margin-right: 10px;
}

使用第三方库(如 vue-horizontal)

安装 vue-horizontal 库:

vue横向滑动实现

npm install vue-horizontal

使用示例:

vue横向滑动实现

<template>
  <vue-horizontal>
    <div v-for="item in items" :key="item.id">
      {{ item.content }}
    </div>
  </vue-horizontal>
</template>

<script>
import VueHorizontal from "vue-horizontal";

export default {
  components: { VueHorizontal },
  data() {
    return {
      items: [...]
    }
  }
}
</script>

使用 touch 事件实现自定义滑动

通过监听 touch 事件计算滑动距离,结合 CSS transform 实现平滑滑动。

<div 
  class="custom-scroll" 
  @touchstart="handleTouchStart"
  @touchmove="handleTouchMove"
  @touchend="handleTouchEnd"
  :style="{ transform: `translateX(${offsetX}px)` }"
>
  <div v-for="item in items" :key="item.id" class="item">
    {{ item.content }}
  </div>
</div>
export default {
  data() {
    return {
      offsetX: 0,
      startX: 0,
      isDragging: false
    }
  },
  methods: {
    handleTouchStart(e) {
      this.startX = e.touches[0].clientX
      this.isDragging = true
    },
    handleTouchMove(e) {
      if (!this.isDragging) return
      const x = e.touches[0].clientX
      this.offsetX += (x - this.startX)
      this.startX = x
    },
    handleTouchEnd() {
      this.isDragging = false
    }
  }
}
.custom-scroll {
  display: flex;
  transition: transform 0.3s ease;
}

.item {
  flex-shrink: 0;
  width: 200px;
}

使用 CSS scroll-snap 实现对齐效果

在滑动容器上添加 scroll-snap 属性,使滑动后自动对齐到最近的子元素。

.scroll-container {
  scroll-snap-type: x mandatory;
  overflow-x: auto;
  display: flex;
}

.scroll-item {
  scroll-snap-align: start;
  flex-shrink: 0;
}

注意事项

  • 移动端开发时需要考虑 touch 事件的兼容性
  • 性能优化:大量子元素时建议使用虚拟滚动
  • 滑动边界处理:限制最大最小偏移量
  • 桌面端兼容:同时监听 mouse 事件

标签: 横向vue
分享给朋友:

相关文章

vue实现展开与收起

vue实现展开与收起

Vue 实现展开与收起功能 在 Vue 中实现展开与收起功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-show 或 v-if 控制显示 通过 Vue 的指令 v-show 或 v-i…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独…

vue datepicker 实现

vue datepicker 实现

实现 Vue Datepicker 的基本方法 在 Vue 项目中实现日期选择功能,可以使用第三方库如 vue-datepicker 或 v-calendar。以下是两种常见实现方式: 安装 vu…

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue 实现递归

vue 实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据,例如菜单、评论列表或文件目录。以下是实现递归组件的关键步骤: 定义递归组件 递归组件需要设置 name 属性,以便在模…

vue底层实现

vue底层实现

Vue.js 的底层实现原理 Vue.js 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是其关键实现细节: 响应式系统 Vue…