需要实现的效果如下:
踩坑经历:mock数据只创建了3条
- 情景1:导致loop为false状态下,页面只显示右侧的边缘和中间内容,左侧边缘不展示
-
情景2:导致loop为true状态下,页面只显示左侧的边缘和中间内容,右侧边缘不展示
解决方案:mock数据增加为4条
参考文章有:https://blog.csdn.net/qq_43231248/article/details/132106493
完整代码
<template>
<div class="banner_box">
<swiper
:loop="true"
:slidesPerView="'auto'"
:spaceBetween="10"
:centeredSlides="true"
:pagination="{ clickable: true}"
:autoplay="{
delay: 2500,
disableOnInteraction: false
}"
:modules="modules"
>
<swiper-slide
v-for="info in banners"
:key="info.id">
<img :src="info.image" alt="" />
</swiper-slide>
</swiper>
</div>
</template>
<script>
// import Swiper core and required modules
import {Autoplay, Pagination, A11y } from 'swiper/modules';
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue';
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/autoplay';
import 'swiper/css/pagination';
import 'swiper/css/a11y';
// Import Swiper styles
export default {
components: {
Swiper,
SwiperSlide,
},
setup() {
return {
banners:[
{
title: 'banner1',
image: 'https://cdn.wwads.cn/creatives/DQ0ejr8o40vUKOK0EyTjFepFuOUzX9bUJtKM9NeC.png'
},
{
title: 'banner2',
image: 'https://cdn.wwads.cn/creatives/DQ0ejr8o40vUKOK0EyTjFepFuOUzX9bUJtKM9NeC.png'
},
{
title: 'banner3',
image: 'https://cdn.wwads.cn/creatives/DQ0ejr8o40vUKOK0EyTjFepFuOUzX9bUJtKM9NeC.png'
},
{
title: 'banner4',
image: 'https://cdn.wwads.cn/creatives/DQ0ejr8o40vUKOK0EyTjFepFuOUzX9bUJtKM9NeC.png'
}
],
modules: [Autoplay, Pagination, A11y],
};
},
};
</script>
<style lang="stylus" scoped>
.banner_box
width 100%
height 144px
background #f8f8f8
overflow hidden
.swiper
height 100%
.swiper-wrapper
height 100%
.swiper-slide
width 336px !important
height 100%
background-repeat no-repeat
background-size cover
background-position center
border-radius 12px
overflow: hidden
img
display block
width 100%
height 100%
</style>
注意:代码主题使用<script setup></script> 也会导致效果显示不出来