当前位置:首页 > VUE

vue横向滑动实现

2026-03-10 02:21:03VUE

Vue 横向滑动实现方法

使用 CSS Flexbox 布局

通过 display: flexoverflow-x: auto 实现横向滚动容器,子元素设置 flex-shrink: 0 防止挤压。

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

<style scoped>
.horizontal-scroll {
  display: flex;
  overflow-x: auto;
  gap: 16px; /* 可选间距 */
  padding: 8px 0;
}
.scroll-item {
  flex-shrink: 0;
  width: 120px; /* 固定宽度示例 */
}
</style>

使用第三方库(如 Swiper)

安装 Swiper 库后,可直接实现丰富的滑动效果,支持触摸和响应式。

npm install swiper@8
<template>
  <swiper :slides-per-view="3" :space-between="20">
    <swiper-slide v-for="item in items" :key="item.id">
      {{ item.content }}
    </swiper-slide>
  </swiper>
</template>

<script>
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';

export default {
  components: { Swiper, SwiperSlide }
};
</script>

监听滚动事件实现动态效果

结合 @scroll 事件和 ref 实现滚动交互逻辑,如显示/隐藏导航按钮。

<template>
  <div ref="scrollContainer" class="scroll-container" @scroll="handleScroll">
    <!-- 内容 -->
  </div>
  <button v-if="showLeftNav" @click="scrollLeft">←</button>
</template>

<script>
export default {
  methods: {
    scrollLeft() {
      this.$refs.scrollContainer.scrollBy({ left: -200, behavior: 'smooth' });
    },
    handleScroll() {
      this.showLeftNav = this.$refs.scrollContainer.scrollLeft > 0;
    }
  }
};
</script>

响应式宽度调整

通过计算属性动态设置子元素宽度,适应不同屏幕尺寸。

vue横向滑动实现

computed: {
  itemWidth() {
    return window.innerWidth < 768 ? '100px' : '150px';
  }
}

注意事项

  • 移动端需添加 -webkit-overflow-scrolling: touch 提升滚动流畅度。
  • 避免在滚动容器内使用过多复杂元素,可能影响性能。
  • 若需无限滚动,可结合虚拟滚动技术(如 vue-virtual-scroller)。

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

相关文章

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

vue实现mvvm

vue实现mvvm

Vue 实现 MVVM 模式 MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 是其典型实现之一。MVVM 的核心是通过数据绑定和响应式系统实现视图与数据的自动同步。…

vue实现语言切换

vue实现语言切换

Vue 实现语言切换的方法 使用 vue-i18n 插件 安装 vue-i18n 插件: npm install vue-i18n 在项目中配置 vue-i18n: import Vue from…

vue实现定位效果

vue实现定位效果

使用Geolocation API实现定位 在Vue中可以通过浏览器内置的Geolocation API获取用户位置信息。需要在组件的mounted钩子中调用相关方法: mounted() {…

vue实现增量更新

vue实现增量更新

Vue 实现增量更新的方法 使用动态组件和 v-if 控制渲染 通过 v-if 或 v-show 控制组件的渲染,避免不必要的 DOM 操作。动态组件结合 keep-alive 可以缓存组件状态,减少…