vue实现内容轮播
使用 Vue 实现内容轮播
基础轮播实现
安装依赖(如使用第三方库)
若选择 vue-awesome-swiper,通过以下命令安装:
npm install swiper vue-awesome-swiper
引入库并配置
在组件中导入并注册:
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
components: { Swiper, SwiperSlide },
data() {
return {
swiperOptions: {
autoplay: {
delay: 3000,
},
loop: true,
pagination: {
el: '.swiper-pagination',
},
},
slides: ['Slide 1', 'Slide 2', 'Slide 3']
};
}
};
模板结构
<swiper :options="swiperOptions">
<swiper-slide v-for="(slide, index) in slides" :key="index">
{{ slide }}
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
纯 Vue 实现(无依赖)
数据与逻辑

data() {
return {
currentIndex: 0,
slides: ['Content 1', 'Content 2', 'Content 3'],
interval: null
};
},
mounted() {
this.startAutoPlay();
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.nextSlide();
}, 3000);
},
nextSlide() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
prevSlide() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
}
}
模板与样式
<div class="carousel">
<button @click="prevSlide">Prev</button>
<div class="slide">{{ slides[currentIndex] }}</div>
<button @click="nextSlide">Next</button>
</div>
<style>
.carousel {
display: flex;
align-items: center;
}
.slide {
margin: 0 20px;
}
</style>
动画增强
添加过渡效果
修改模板部分:

<transition name="fade" mode="out-in">
<div class="slide" :key="currentIndex">
{{ slides[currentIndex] }}
</div>
</transition>
CSS 过渡样式
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
响应式控制
根据屏幕尺寸调整参数
computed: {
swiperOptions() {
return {
slidesPerView: window.innerWidth < 768 ? 1 : 3,
spaceBetween: 30
};
}
}
监听窗口变化
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}






