vue实现列表左右滑动
实现列表左右滑动的 Vue 方案
使用 CSS 和 Touch 事件
通过 CSS 的 overflow-x: auto 和 white-space: nowrap 实现横向滚动容器,结合 Vue 的 @touchstart、@touchmove 事件处理滑动逻辑:
<template>
<div
class="scroll-container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
ref="container"
>
<div class="item" v-for="item in items" :key="item.id">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 你的列表数据
startX: 0,
scrollLeft: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].pageX
this.scrollLeft = this.$refs.container.scrollLeft
},
handleTouchMove(e) {
const x = e.touches[0].pageX
const walk = (x - this.startX) * 2 // 调节滑动灵敏度
this.$refs.container.scrollLeft = this.scrollLeft - walk
}
}
}
</script>
<style>
.scroll-container {
display: flex;
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}
.item {
flex: 0 0 auto;
width: 100px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用第三方库(Better-Scroll)
Better-Scroll 提供更流畅的滑动体验和额外功能(如惯性滚动、边界回弹):

npm install @better-scroll/core
<template>
<div ref="wrapper" class="wrapper">
<div class="content">
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</div>
</div>
</template>
<script>
import BScroll from '@better-scroll/core'
export default {
data() {
return {
items: [...] // 你的列表数据
}
},
mounted() {
this.bs = new BScroll(this.$refs.wrapper, {
scrollX: true,
scrollY: false,
momentum: true,
bounce: true
})
},
beforeDestroy() {
this.bs.destroy()
}
}
</script>
<style>
.wrapper {
width: 100%;
overflow: hidden;
}
.content {
display: inline-block;
white-space: nowrap;
}
.item {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用 Swiper 组件
Swiper 是专业的轮播图/滑动库,适合复杂场景:

npm install swiper@6
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="item in items" :key="item.id">
{{ item.text }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
export default {
components: { Swiper, SwiperSlide },
data() {
return {
items: [...],
swiperOptions: {
slidesPerView: 'auto',
spaceBetween: 10,
freeMode: true
}
}
}
}
</script>
<style>
.swiper-slide {
width: auto;
height: 100px;
background: #eee;
}
</style>
响应式注意事项
对于需要响应式布局的情况,可以通过监听窗口变化动态调整:
export default {
// ...
methods: {
updateSlider() {
if (this.bs) {
this.bs.refresh()
}
}
},
mounted() {
window.addEventListener('resize', this.updateSlider)
},
beforeDestroy() {
window.removeEventListener('resize', this.updateSlider)
}
}
性能优化建议
对于长列表,建议使用虚拟滚动技术(如 vue-virtual-scroller)避免渲染大量 DOM 节点:
npm install vue-virtual-scroller
<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="100"
direction="horizontal"
key-field="id"
>
<template v-slot="{ item }">
<div class="item">
{{ item.text }}
</div>
</template>
</RecycleScroller>
</template>






