vue3实现轮播
Vue3 实现轮播功能
使用 Vue3 实现轮播功能可以通过多种方式完成,以下是几种常见的方法:
使用第三方库(如 Swiper)
Swiper 是一个流行的轮播库,支持 Vue3,功能强大且易于使用。
安装 Swiper:
npm install swiper vue-awesome-swiper
基本使用示例:
<template>
<swiper
:modules="modules"
:slides-per-view="1"
:space-between="50"
navigation
:pagination="{ clickable: true }"
>
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title">
</swiper-slide>
</swiper>
</template>
<script setup>
import { ref } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation, Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
const modules = [Navigation, Pagination];
const slides = ref([
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' },
]);
</script>
自定义轮播组件
如果需要更轻量级的解决方案,可以自定义轮播组件。
基础实现代码:
<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">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const currentIndex = ref(0);
const slides = ref([
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' },
]);
const prev = () => {
currentIndex.value = currentIndex.value === 0 ? slides.value.length - 1 : currentIndex.value - 1;
};
const next = () => {
currentIndex.value = currentIndex.value === slides.value.length - 1 ? 0 : currentIndex.value + 1;
};
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
自动轮播功能
为自定义轮播添加自动播放功能:
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const currentIndex = ref(0);
const slides = ref([...]);
let intervalId;
const startAutoPlay = () => {
intervalId = setInterval(() => {
next();
}, 3000);
};
const stopAutoPlay = () => {
clearInterval(intervalId);
};
onMounted(() => {
startAutoPlay();
});
onUnmounted(() => {
stopAutoPlay();
});
</script>
响应式设计
确保轮播在不同屏幕尺寸下正常工作:
@media (max-width: 768px) {
.carousel {
width: 100%;
}
.slide img {
width: 100%;
height: auto;
}
}
以上方法提供了从简单到复杂的轮播实现方案,可根据项目需求选择适合的方式。







