vue实现焦点轮播
Vue 实现焦点轮播的方法
使用 Vue 和 CSS 实现基础轮播
创建一个 Vue 组件,利用 v-for 渲染轮播项,通过 CSS 控制显示和隐藏。
<template>
<div class="carousel">
<div
v-for="(item, index) in items"
:key="index"
class="carousel-item"
:class="{ 'active': currentIndex === index }"
>
{{ item }}
</div>
<button @click="prev">Previous</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
items: ['Item 1', 'Item 2', 'Item 3']
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length;
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length;
}
}
}
</script>
<style>
.carousel {
position: relative;
overflow: hidden;
}
.carousel-item {
display: none;
width: 100%;
}
.carousel-item.active {
display: block;
}
</style>
添加自动轮播功能
在组件中增加定时器,实现自动轮播效果。
export default {
data() {
return {
currentIndex: 0,
items: ['Item 1', 'Item 2', 'Item 3'],
interval: null
}
},
mounted() {
this.startAutoPlay();
},
beforeDestroy() {
this.stopAutoPlay();
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.next();
}, 3000);
},
stopAutoPlay() {
clearInterval(this.interval);
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length;
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length;
}
}
}
实现平滑过渡效果
通过 CSS 过渡属性添加平滑的动画效果。
.carousel-item {
position: absolute;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.carousel-item.active {
opacity: 1;
}
使用第三方库实现更复杂功能
如果需要更复杂的功能(如无限循环、触摸滑动等),可以考虑使用专门的轮播库:

-
Vue-Awesome-Swiper
安装命令:npm install swiper vue-awesome-swiper --save使用示例:

<template> <swiper :options="swiperOptions"> <swiper-slide v-for="(item, index) in items" :key="index"> {{ item }} </swiper-slide> <div class="swiper-pagination" slot="pagination"></div> </swiper> </template> <script> import { Swiper, SwiperSlide } from 'vue-awesome-swiper' import 'swiper/css/swiper.css' export default { components: { Swiper, SwiperSlide }, data() { return { items: ['Item 1', 'Item 2', 'Item 3'], swiperOptions: { pagination: { el: '.swiper-pagination' }, autoplay: { delay: 3000 } } } } } </script> -
Vue-Carousel
另一个轻量级选择,安装命令:npm install vue-carousel --save
添加焦点管理
确保轮播在键盘导航时可访问:
methods: {
handleKeydown(event) {
if (event.key === 'ArrowLeft') {
this.prev();
} else if (event.key === 'ArrowRight') {
this.next();
}
}
},
mounted() {
window.addEventListener('keydown', this.handleKeydown);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeydown);
}
响应式设计考虑
使用 CSS 媒体查询确保轮播在不同设备上表现良好:
@media (max-width: 768px) {
.carousel {
width: 100%;
}
.carousel-item {
font-size: 14px;
}
}






