vue实现水平滚动
Vue 实现水平滚动的几种方法
使用 CSS 的 overflow-x 和 white-space
在 Vue 组件中,可以通过 CSS 的 overflow-x 和 white-space 属性实现水平滚动。这种方法适用于内容宽度超出容器宽度时自动显示滚动条。
<template>
<div class="horizontal-scroll-container">
<div class="horizontal-scroll-content">
<!-- 内容项 -->
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.text }}
</div>
</div>
</div>
</template>
<style>
.horizontal-scroll-container {
overflow-x: auto;
white-space: nowrap;
}
.horizontal-scroll-content {
display: inline-block;
}
.scroll-item {
display: inline-block;
width: 200px;
height: 100px;
margin-right: 10px;
background: #f0f0f0;
}
</style>
使用 Flexbox 布局
Flexbox 布局可以更方便地实现水平滚动,尤其是当内容项需要动态调整大小时。

<template>
<div class="flex-scroll-container">
<div v-for="item in items" :key="item.id" class="flex-scroll-item">
{{ item.text }}
</div>
</div>
</template>
<style>
.flex-scroll-container {
display: flex;
overflow-x: auto;
gap: 10px;
}
.flex-scroll-item {
flex: 0 0 auto;
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>
使用第三方库(如 Vue-Slick)
如果需要更复杂的功能(如分页、自动滚动),可以使用第三方库如 vue-slick。
安装 vue-slick:

npm install vue-slick-carousel
使用示例:
<template>
<div>
<VueSlickCarousel :arrows="true" :dots="true">
<div v-for="item in items" :key="item.id">
<h3>{{ item.text }}</h3>
</div>
</VueSlickCarousel>
</div>
</template>
<script>
import VueSlickCarousel from 'vue-slick-carousel';
import 'vue-slick-carousel/dist/vue-slick-carousel.css';
export default {
components: { VueSlickCarousel },
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
],
};
},
};
</script>
自定义滚动行为
如果需要自定义滚动行为(如按钮控制滚动),可以通过监听事件和操作 DOM 实现。
<template>
<div>
<div ref="scrollContainer" class="custom-scroll-container">
<div v-for="item in items" :key="item.id" class="custom-scroll-item">
{{ item.text }}
</div>
</div>
<button @click="scrollLeft">向左滚动</button>
<button @click="scrollRight">向右滚动</button>
</div>
</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({ left: -200, behavior: 'smooth' });
},
scrollRight() {
this.$refs.scrollContainer.scrollBy({ left: 200, behavior: 'smooth' });
},
},
};
</script>
<style>
.custom-scroll-container {
display: flex;
overflow-x: auto;
gap: 10px;
}
.custom-scroll-item {
flex: 0 0 auto;
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>






