vue实现内容左右滑动
Vue 实现内容左右滑动的方法
使用 CSS 和 touch 事件
通过 CSS 的 overflow-x: auto 和 touch 事件实现左右滑动效果。
<template>
<div class="scroll-container" ref="scrollContainer" @touchstart="handleTouchStart" @touchmove="handleTouchMove">
<div class="scroll-content">
<!-- 你的内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
scrollLeft: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].pageX
this.scrollLeft = this.$refs.scrollContainer.scrollLeft
},
handleTouchMove(e) {
const x = e.touches[0].pageX
const walk = (x - this.startX) * 2
this.$refs.scrollContainer.scrollLeft = this.scrollLeft - walk
}
}
}
</script>
<style>
.scroll-container {
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
.scroll-content {
display: inline-block;
}
</style>
使用第三方库(如 Swiper)
安装 Swiper 库并配置 Vue 组件。
npm install swiper
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(item, index) in items" :key="index">
<!-- 你的内容 -->
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
swiperOptions: {
slidesPerView: 'auto',
spaceBetween: 10,
freeMode: true
},
items: [/* 你的数据 */]
}
}
}
</script>
使用 CSS Scroll Snap
利用 CSS 的 scroll-snap 特性实现平滑滑动。
<template>
<div class="scroll-snap-container">
<div class="scroll-snap-content" v-for="(item, index) in items" :key="index">
<!-- 你的内容 -->
</div>
</div>
</template>
<style>
.scroll-snap-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
}
.scroll-snap-content {
scroll-snap-align: start;
flex: 0 0 auto;
width: 80%;
margin-right: 10px;
}
</style>
使用 Vue 指令实现
自定义 Vue 指令处理滑动逻辑。
Vue.directive('horizontal-scroll', {
inserted(el) {
el.addEventListener('touchstart', handleTouchStart)
el.addEventListener('touchmove', handleTouchMove)
let startX, scrollLeft
function handleTouchStart(e) {
startX = e.touches[0].pageX
scrollLeft = el.scrollLeft
}
function handleTouchMove(e) {
const x = e.touches[0].pageX
const walk = (x - startX) * 2
el.scrollLeft = scrollLeft - walk
}
}
})
<template>
<div v-horizontal-scroll class="scroll-container">
<!-- 你的内容 -->
</div>
</template>






