vue实现水平滚动
Vue 实现水平滚动的方法
使用 CSS 的 overflow-x 属性
在 Vue 组件的模板中,创建一个容器元素,并为其添加 overflow-x: auto 样式。确保子元素宽度超过容器宽度。
<template>
<div class="scroll-container">
<div class="scroll-content">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.text }}
</div>
</div>
</div>
</template>
<style scoped>
.scroll-container {
width: 100%;
overflow-x: auto;
white-space: nowrap;
}
.scroll-content {
display: inline-block;
}
.scroll-item {
display: inline-block;
width: 200px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用第三方库(如 vue-horizontal-scroll)
安装 vue-horizontal-scroll 库:

npm install vue-horizontal-scroll
在 Vue 组件中使用:

<template>
<vue-horizontal-scroll>
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</vue-horizontal-scroll>
</template>
<script>
import VueHorizontalScroll from 'vue-horizontal-scroll'
export default {
components: {
VueHorizontalScroll
},
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
}
}
</script>
<style scoped>
.item {
width: 200px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用 CSS Flexbox 布局
通过 Flexbox 实现水平滚动,确保子元素不换行。
<template>
<div class="flex-scroll">
<div v-for="item in items" :key="item.id" class="flex-item">
{{ item.text }}
</div>
</div>
</template>
<style scoped>
.flex-scroll {
display: flex;
overflow-x: auto;
width: 100%;
}
.flex-item {
flex: 0 0 auto;
width: 200px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用 JavaScript 控制滚动
通过 Vue 的 ref 和 JavaScript 控制滚动行为。
<template>
<div ref="scrollContainer" class="js-scroll">
<div v-for="item in items" :key="item.id" class="js-item">
{{ item.text }}
</div>
</div>
<button @click="scrollLeft">Scroll Left</button>
<button @click="scrollRight">Scroll Right</button>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
},
methods: {
scrollLeft() {
this.$refs.scrollContainer.scrollBy(-100, 0)
},
scrollRight() {
this.$refs.scrollContainer.scrollBy(100, 0)
}
}
}
</script>
<style scoped>
.js-scroll {
display: flex;
overflow-x: auto;
width: 100%;
}
.js-item {
flex: 0 0 auto;
width: 200px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
注意事项
- 确保容器宽度有限,子元素宽度总和超过容器宽度才能触发滚动。
- 使用
white-space: nowrap或flex-wrap: nowrap防止子元素换行。 - 对于触控设备,可以添加
-webkit-overflow-scrolling: touch以启用平滑滚动。






