vue实现轮播图代码
Vue实现轮播图代码
以下是一个基于Vue 3的轮播图实现示例,包含自动轮播、手动切换和指示器功能。
基础结构
<template>
<div class="carousel-container">
<div class="carousel" @mouseenter="pause" @mouseleave="resume">
<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.alt">
</div>
</div>
<button class="prev" @click="prev">‹</button>
<button class="next" @click="next">›</button>
<div class="indicators">
<span
v-for="(item, index) in slides"
:key="index"
:class="{ active: currentIndex === index }"
@click="goTo(index)"
></span>
</div>
</div>
</div>
</template>
脚本部分
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const slides = ref([
{ image: 'image1.jpg', alt: 'Image 1' },
{ image: 'image2.jpg', alt: 'Image 2' },
{ image: 'image3.jpg', alt: 'Image 3' }
]);
const currentIndex = ref(0);
let intervalId = null;
const autoPlayDelay = 3000;
const next = () => {
currentIndex.value = (currentIndex.value + 1) % slides.value.length;
};
const prev = () => {
currentIndex.value = (currentIndex.value - 1 + slides.value.length) % slides.value.length;
};
const goTo = (index) => {
currentIndex.value = index;
};
const startAutoPlay = () => {
intervalId = setInterval(next, autoPlayDelay);
};
const pause = () => {
clearInterval(intervalId);
};
const resume = () => {
startAutoPlay();
};
onMounted(() => {
startAutoPlay();
});
onUnmounted(() => {
pause();
});
return {
slides,
currentIndex,
next,
prev,
goTo,
pause,
resume
};
}
};
</script>
样式部分
<style scoped>
.carousel-container {
width: 100%;
max-width: 800px;
margin: 0 auto;
overflow: hidden;
position: relative;
}
.carousel {
position: relative;
height: 400px;
}
.slides {
display: flex;
transition: transform 0.5s ease;
height: 100%;
}
.slide {
min-width: 100%;
height: 100%;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0,0,0,0.5);
color: white;
border: none;
padding: 10px 15px;
cursor: pointer;
z-index: 10;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
.indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
}
.indicators span {
width: 12px;
height: 12px;
border-radius: 50%;
background: rgba(255,255,255,0.5);
cursor: pointer;
}
.indicators span.active {
background: white;
}
</style>
功能说明
- 自动轮播:组件挂载后自动开始轮播,3秒切换一次
- 鼠标悬停暂停:鼠标移入轮播区域时暂停自动播放
- 导航按钮:提供上一张/下一张的手动切换按钮
- 指示器:底部圆点指示当前幻灯片位置,可点击跳转
- 平滑过渡:使用CSS transition实现平滑的滑动效果
扩展建议
- 添加淡入淡出效果:修改CSS transition属性
- 无限循环:克隆首尾幻灯片实现无缝循环
- 响应式设计:添加媒体查询适应不同屏幕尺寸
- 懒加载:对未显示的图片实现懒加载
- 触摸支持:添加touch事件处理移动端滑动







