vue走马灯实现
Vue 走马灯实现方法
使用第三方库(如 Swiper)
安装 Swiper 库:
npm install swiper
在 Vue 组件中引入并使用:
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</template>
<script>
import Swiper from 'swiper'
import 'swiper/swiper-bundle.css'
export default {
data() {
return {
items: ['Slide 1', 'Slide 2', 'Slide 3']
}
},
mounted() {
new Swiper('.swiper-container', {
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
})
}
}
</script>
<style>
.swiper-container {
width: 100%;
height: 300px;
}
</style>
使用 Element UI 的 Carousel 组件
安装 Element UI:
npm install element-ui
在 Vue 项目中使用:
<template>
<el-carousel :interval="3000" type="card" height="200px">
<el-carousel-item v-for="(item, index) in items" :key="index">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<script>
import { ElCarousel, ElCarouselItem } from 'element-ui'
export default {
components: {
ElCarousel,
ElCarouselItem
},
data() {
return {
items: ['Slide 1', 'Slide 2', 'Slide 3']
}
}
}
</script>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
line-height: 200px;
margin: 0;
text-align: center;
}
</style>
自定义实现走马灯效果
<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div class="slide" v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Slide 1', 'Slide 2', 'Slide 3'],
currentIndex: 0,
timer: null
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
},
startAutoPlay() {
this.timer = setInterval(this.next, 3000)
},
stopAutoPlay() {
clearInterval(this.timer)
}
},
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
this.stopAutoPlay()
}
}
</script>
<style>
.carousel {
width: 100%;
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
flex: 0 0 100%;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
</style>
实现要点
- 自动轮播:通过 setInterval 实现定时切换,注意组件销毁时清除定时器
- 无限循环:通过取模运算实现首尾衔接的循环效果
- 平滑过渡:使用 CSS transform 和 transition 实现平滑滑动效果
- 响应式设计:确保走马灯在不同屏幕尺寸下正常显示
- 用户交互:添加鼠标悬停暂停、左右箭头导航等功能提升用户体验
性能优化建议
- 使用 will-change 属性优化动画性能
- 对大量图片实现懒加载
- 避免频繁的 DOM 操作
- 使用 requestAnimationFrame 替代 setInterval 实现动画







