vue实现列表横向滑动
实现列表横向滑动的方法
在Vue中实现列表横向滑动可以通过CSS和Vue指令结合完成。以下是具体实现方式:

使用CSS flex布局
<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-flex;
}
.scroll-item {
min-width: 100px;
height: 100px;
margin-right: 10px;
background: #eee;
display: inline-block;
}
</style>
使用第三方库(如vue-horizontal)
安装vue-horizontal库:

npm install vue-horizontal
使用示例:
<template>
<vue-horizontal>
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
</vue-horizontal>
</template>
<script>
import VueHorizontal from "vue-horizontal";
export default {
components: {VueHorizontal},
data() {
return {
items: [...]
}
}
}
</script>
使用CSS Grid布局
<template>
<div class="grid-scroll">
<div v-for="item in items" :key="item.id" class="grid-item">
{{ item.text }}
</div>
</div>
</template>
<style scoped>
.grid-scroll {
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(100px, 1fr);
overflow-x: auto;
gap: 10px;
}
.grid-item {
height: 100px;
background: #eee;
}
</style>
添加平滑滚动效果
可以通过JavaScript添加平滑滚动行为:
<template>
<div ref="scrollContainer" class="scroll-container">
<div class="scroll-content">
<!-- 内容 -->
</div>
<button @click="scrollLeft">左滑</button>
<button @click="scrollRight">右滑</button>
</div>
</template>
<script>
export default {
methods: {
scrollLeft() {
this.$refs.scrollContainer.scrollBy({
left: -200,
behavior: 'smooth'
});
},
scrollRight() {
this.$refs.scrollContainer.scrollBy({
left: 200,
behavior: 'smooth'
});
}
}
}
</script>
注意事项
- 移动端需要添加
-webkit-overflow-scrolling: touch增强滚动体验 - 考虑添加阴影或渐变效果提示用户可滚动
- 对于大量数据,建议实现虚拟滚动优化性能
以上方法可以根据具体需求选择使用,CSS方案简单轻量,第三方库提供更多功能但增加依赖。






