vue页面实现轮播图
使用 Swiper 实现轮播图
Swiper 是一个流行的开源轮播图库,支持 Vue 集成。安装 Swiper 及相关依赖:
npm install swiper vue-awesome-swiper
在 Vue 组件中引入 Swiper:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title" />
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/swiper-bundle.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination',
clickable: true
},
loop: true,
autoplay: {
delay: 3000,
disableOnInteraction: false
}
}
}
}
}
</script>
<style scoped>
.swiper-container {
width: 100%;
height: 300px;
}
</style>
使用纯 Vue 实现简单轮播
无需第三方库,通过 Vue 的数据绑定和计算属性实现基础轮播:
<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div v-for="(slide, index) in slides" :key="index" class="slide">
<img :src="slide.image" :alt="slide.title" />
</div>
</div>
<button @click="prev">Previous</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
]
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
}
},
mounted() {
setInterval(this.next, 3000)
}
}
</script>
<style scoped>
.carousel {
overflow: hidden;
position: relative;
width: 100%;
height: 300px;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
使用 Element UI 的轮播组件
如果项目中使用 Element UI,可以直接使用其 Carousel 组件:
<template>
<el-carousel :interval="3000" type="card" height="300px">
<el-carousel-item v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title" />
</el-carousel-item>
</el-carousel>
</template>
<script>
export default {
data() {
return {
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
]
}
}
}
</script>
关键注意事项
轮播图宽度应设置为 100% 或固定值,避免布局问题 图片资源建议使用绝对路径或通过 require 引入 移动端需考虑触摸滑动支持,Swiper 已内置此功能 自动轮播时注意内存泄漏,组件销毁前清除定时器







