vue 实现div横向滚动
实现横向滚动的基本方法
在Vue中实现div横向滚动可以通过CSS的overflow-x属性结合white-space或Flexbox布局完成。以下是两种常见实现方式:
方法一:使用inline-block元素

<template>
<div class="scroll-container">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
</template>
<style scoped>
.scroll-container {
overflow-x: auto;
white-space: nowrap;
width: 100%;
-webkit-overflow-scrolling: touch; /* 优化iOS滚动 */
}
.scroll-item {
display: inline-block;
width: 200px;
height: 100px;
margin-right: 10px;
}
</style>
方法二:使用Flexbox布局

<template>
<div class="scroll-container">
<div class="scroll-wrapper">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
</div>
</template>
<style scoped>
.scroll-container {
overflow-x: auto;
width: 100%;
}
.scroll-wrapper {
display: flex;
flex-wrap: nowrap;
padding: 10px 0;
}
.scroll-item {
flex: 0 0 auto;
width: 200px;
margin-right: 10px;
}
</style>
添加滚动阴影效果
为增强用户体验,可以通过伪元素添加滚动边界提示:
.scroll-container {
position: relative;
}
.scroll-container::after {
content: "";
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 30px;
background: linear-gradient(to right, transparent, rgba(0,0,0,0.1));
pointer-events: none;
}
响应式处理
结合Vue的响应式特性,动态计算容器宽度:
export default {
data() {
return {
items: [...],
containerWidth: 0
}
},
mounted() {
this.updateWidth()
window.addEventListener('resize', this.updateWidth)
},
beforeDestroy() {
window.removeEventListener('resize', this.updateWidth)
},
methods: {
updateWidth() {
this.containerWidth = this.$el.offsetWidth
}
}
}
性能优化建议
- 对大量滚动元素使用
v-show替代v-if避免重复渲染 - 添加
will-change: transform提升滚动性能 - 使用
Intersection Observer API实现懒加载 - 移动端可添加
-webkit-overflow-scrolling: touch启用弹性滚动
完整组件示例
<template>
<div ref="container" class="horizontal-scroll">
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: 'HorizontalScroll',
mounted() {
this.initScroll()
},
methods: {
initScroll() {
const container = this.$refs.container
container.addEventListener('wheel', (e) => {
if (e.deltaY !== 0) {
e.preventDefault()
container.scrollLeft += e.deltaY
}
}, { passive: false })
}
}
}
</script>
<style scoped>
.horizontal-scroll {
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
}
.horizontal-scroll::-webkit-scrollbar {
display: none;
}
.content {
display: inline-flex;
min-width: 100%;
}
</style>






