vue轮播图简单实现
使用 Vue 实现轮播图
以下是一个基于 Vue 3 的简单轮播图实现方法,无需依赖第三方库。
基础结构
在 Vue 单文件组件中,通过 v-for 渲染图片列表,并用 CSS 控制切换效果。
<template>
<div class="carousel-container">
<div class="carousel" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div
v-for="(image, index) in images"
:key="index"
class="slide"
>
<img :src="image" alt="轮播图">
</div>
</div>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
</div>
</template>
数据与逻辑
通过 currentIndex 控制当前显示的图片位置,添加自动轮播功能。
<script>
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
currentIndex: 0,
intervalId: null
}
},
mounted() {
this.startAutoPlay()
},
beforeUnmount() {
clearInterval(this.intervalId)
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
},
startAutoPlay() {
this.intervalId = setInterval(this.next, 3000)
}
}
}
</script>
样式设计
使用 CSS 实现横向滑动效果,注意隐藏超出部分。
<style scoped>
.carousel-container {
width: 100%;
overflow: hidden;
position: relative;
}
.carousel {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
.slide img {
width: 100%;
height: auto;
}
</style>
添加指示器
在模板中添加指示器点,实时反映当前激活的图片。
<div class="indicators">
<span
v-for="(_, index) in images"
:key="index"
:class="{ active: currentIndex === index }"
@click="currentIndex = index"
></span>
</div>
对应的 CSS 样式:
.indicators {
display: flex;
justify-content: center;
margin-top: 10px;
}
.indicators span {
width: 12px;
height: 12px;
margin: 0 5px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
.indicators span.active {
background-color: #333;
}
优化交互
添加鼠标悬停暂停自动轮播的功能。
methods: {
pauseAutoPlay() {
clearInterval(this.intervalId)
},
resumeAutoPlay() {
this.startAutoPlay()
}
}
在模板容器上添加事件:
<div
class="carousel-container"
@mouseenter="pauseAutoPlay"
@mouseleave="resumeAutoPlay"
>
响应式处理
通过计算属性获取窗口宽度,实现响应式布局。
computed: {
carouselWidth() {
return window.innerWidth > 768 ? '80%' : '100%'
}
}
将计算属性绑定到样式:
<div class="carousel-container" :style="{ width: carouselWidth }">






