轮播图vue实现
使用 Vue 实现轮播图
基础轮播图实现
安装依赖(如需要):
npm install vue-awesome-swiper
引入 Swiper 组件:
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
模板部分:
<swiper>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
</swiper>
自定义配置选项
添加导航和分页:
const swiperOptions = {
navigation: true,
pagination: { clickable: true },
loop: true,
autoplay: {
delay: 3000,
disableOnInteraction: false
}
}
模板绑定配置:
<swiper :modules="modules" :options="swiperOptions">
<!-- slides -->
</swiper>
纯 Vue 实现方案
响应式数据:
data() {
return {
currentIndex: 0,
slides: [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' },
{ id: 3, content: 'Slide 3' }
]
}
}
模板结构:
<div class="carousel">
<div class="slides" :style="slideStyle">
<div v-for="slide in slides" :key="slide.id" class="slide">
{{ slide.content }}
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
计算属性和方法:
computed: {
slideStyle() {
return {
transform: `translateX(-${this.currentIndex * 100}%)`
}
}
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
}
}
过渡动画效果
添加 CSS 过渡:
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
flex: 0 0 100%;
}
自动轮播功能
添加自动轮播:
mounted() {
this.autoPlay = setInterval(this.next, 3000)
},
beforeDestroy() {
clearInterval(this.autoPlay)
}
响应式处理
监听窗口变化:
data() {
return {
windowWidth: window.innerWidth
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
}
}
触摸支持
添加触摸事件:
<div
class="slides"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
>
触摸方法实现:
data() {
return {
touchStartX: 0,
touchEndX: 0
}
},
methods: {
touchStart(e) {
this.touchStartX = e.changedTouches[0].screenX
},
touchEnd(e) {
this.touchEndX = e.changedTouches[0].screenX
this.handleSwipe()
},
handleSwipe() {
if (this.touchEndX < this.touchStartX) this.next()
if (this.touchEndX > this.touchStartX) this.prev()
}
}






