vue3轮播图无缝滚动代码
时间: 2024-06-15 15:01:43 浏览: 164
Vue3中的轮播图无缝滚动通常使用轮播插件或自定义组件来实现,常见的库如`vue-awesome-swiper`或者`vue-slick-carousel`。以下是一个简单的`vue-awesome-swiper`的无缝滚动示例代码:
```html
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(item, index) in items" :key="index">
<img :src="item.src" :alt="item.alt">
</swiper-slide>
<!-- 如果你想添加导航按钮 -->
<div class="swiper-button-prev" @click="prevSlide"></div>
<div class="swiper-button-next" @click="nextSlide"></div>
</swiper>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { swiper, SwiperSlide } from 'vue-awesome-swiper';
const swiperOptions = ref({
// 设置轮播图选项,例如自动播放、循环、速度等
loop: true, // 开启无缝滚动
autoplay: {
delay: 3000, // 每隔3秒切换到下一张
},
pagination: {
el: '.swiper-pagination',
},
});
let currentSlide = ref(0); // 当前索引
onMounted(() => {
// 初始化Swiper实例
const swiperInstance = swiper(swiperOptions.value);
// 监听滑动事件
swiperInstance.on('slideChangeTransitionEnd', () => {
currentSlide.value = swiperInstance.realIndex; // 更新当前索引
});
});
// 方法用于切换到上一张和下一张
function prevSlide() {
if (currentSlide.value > 0) {
currentSlide.value--;
}
}
function nextSlide() {
const slidesCount = swiperOptions.value.slides.length;
if (currentSlide.value + 1 < slidesCount) {
currentSlide.value++;
}
}
</script>
<style scoped>
.swiper-button-prev, .swiper-button-next {
/* 根据你的样式需求进行定制 */
}
</style>
```
阅读全文