vue实现横向点击滑动
Vue 实现横向点击滑动
使用 CSS 和 Vue 事件绑定
通过 CSS 的 overflow-x 和 scroll-behavior 属性实现横向滑动容器,结合 Vue 的 @click 事件触发滚动。
<template>
<div class="scroll-container" ref="scrollContainer">
<div class="scroll-content">
<div v-for="item in items" :key="item.id" class="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" },
// 更多项目...
]
};
},
methods: {
scrollLeft() {
this.$refs.scrollContainer.scrollBy({ left: -200, behavior: 'smooth' });
},
scrollRight() {
this.$refs.scrollContainer.scrollBy({ left: 200, behavior: 'smooth' });
}
}
};
</script>
<style>
.scroll-container {
width: 100%;
overflow-x: auto;
scroll-behavior: smooth;
white-space: nowrap;
}
.scroll-content {
display: inline-flex;
}
.item {
width: 200px;
height: 100px;
margin: 0 10px;
background: #eee;
display: inline-flex;
align-items: center;
justify-content: center;
}
</style>
使用第三方库(如 vue-slick)
vue-slick 是基于 Slick Carousel 的 Vue 封装,适合快速实现轮播或滑动效果。
安装依赖:
npm install vue-slick-carousel
示例代码:
<template>
<vue-slick ref="slick" :options="slickOptions">
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
</vue-slick>
</template>
<script>
import VueSlick from 'vue-slick-carousel';
export default {
components: { VueSlick },
data() {
return {
items: [
{ id: 1, text: "Item 1" },
{ id: 2, text: "Item 2" },
],
slickOptions: {
slidesToShow: 3,
arrows: true,
dots: true,
}
};
}
};
</script>
动态计算滑动距离
通过计算容器宽度和项目宽度,动态调整每次滑动的距离。
methods: {
scrollRight() {
const container = this.$refs.scrollContainer;
const itemWidth = 200; // 单个项目宽度
container.scrollBy({ left: itemWidth, behavior: 'smooth' });
}
}
响应式滑动
结合 ResizeObserver 监听容器宽度变化,动态调整滑动逻辑。
mounted() {
const observer = new ResizeObserver(entries => {
entries.forEach(entry => {
this.containerWidth = entry.contentRect.width;
});
});
observer.observe(this.$refs.scrollContainer);
}
注意事项
- 移动端兼容性:确保添加
touch-actionCSS 属性以支持触摸滑动。 - 性能优化:对于大量数据,建议使用虚拟滚动(如
vue-virtual-scroller)。 - 浏览器支持:
scroll-behavior: smooth在旧版本浏览器中可能需要 polyfill。







