当前位置:首页 > 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 库:

npm install vue-horizontal

使用示例:

<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 属性,使滑动后自动对齐到最近的子元素。

vue横向滑动实现

.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 3的实现方案: 数据结构设计 const timetableData = ref([ { ti…

vue实现缩放

vue实现缩放

Vue 实现缩放的方法 在 Vue 中实现缩放功能可以通过多种方式完成,以下是一些常见的方法: 使用 CSS transform 属性 通过 CSS 的 transform: scale() 属性可…

vue实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdown…

vue实现fadein

vue实现fadein

Vue 实现 FadeIn 效果 在 Vue 中实现淡入(FadeIn)效果可以通过 CSS 过渡、动画或第三方库实现。以下是几种常见方法: 使用 CSS 过渡 通过 Vue 的过渡系统结合 CSS…

vue 实现筛选

vue 实现筛选

实现筛选功能的基本方法 在Vue中实现筛选功能通常涉及以下几个核心步骤: 数据绑定与筛选逻辑 使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选: data() {…

vue 动画实现

vue 动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要分为内置组件和第三方库集成。 使用 Vue 内置过渡组件 Vue 的 <transition> 和 <transiti…