vue实现左右滚动
vue实现左右滚动的方法
使用Vue实现左右滚动可以通过多种方式完成,以下是几种常见的方法:
使用CSS和Vue指令
在Vue模板中,通过CSS的overflow-x属性实现水平滚动,结合Vue的动态绑定控制滚动行为。

<template>
<div class="scroll-container" ref="scrollContainer">
<div class="scroll-content">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
<button @click="scrollLeft">左滚</button>
<button @click="scrollRight">右滚</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
// 更多项目...
]
};
},
methods: {
scrollLeft() {
this.$refs.scrollContainer.scrollBy({ left: -100, behavior: 'smooth' });
},
scrollRight() {
this.$refs.scrollContainer.scrollBy({ left: 100, behavior: 'smooth' });
}
}
};
</script>
<style>
.scroll-container {
width: 300px;
overflow-x: auto;
white-space: nowrap;
}
.scroll-content {
display: inline-block;
}
.scroll-item {
display: inline-block;
width: 100px;
margin-right: 10px;
}
</style>
使用第三方库
如果需要更复杂的滚动效果,可以考虑使用第三方库如vue-smooth-scroll或vue-horizontal-scroll。
安装vue-horizontal-scroll:

npm install vue-horizontal-scroll
使用示例:
<template>
<vue-horizontal>
<section v-for="item in items" :key="item.id">
{{ item.content }}
</section>
</vue-horizontal>
</template>
<script>
import VueHorizontal from 'vue-horizontal';
export default {
components: { VueHorizontal },
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
// 更多项目...
]
};
}
};
</script>
使用触摸事件
在移动端,可以通过监听触摸事件实现左右滑动效果。
<template>
<div
class="scroll-container"
ref="scrollContainer"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
>
<div class="scroll-content">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
// 更多项目...
],
startX: 0
};
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
const moveX = e.touches[0].clientX - this.startX;
this.$refs.scrollContainer.scrollLeft -= moveX;
this.startX = e.touches[0].clientX;
}
}
};
</script>
注意事项
- 确保滚动容器的宽度小于内容的宽度,否则滚动不会生效。
- 使用
white-space: nowrap防止内容换行。 - 对于复杂的滚动需求,建议使用成熟的第三方库以减少开发时间。






