Vue3 swiper 实现 一页显示3个 中间居中两边显示边缘

需要实现的效果如下:

目标效果

踩坑经历:mock数据只创建了3条

  • 情景1:导致loop为false状态下,页面只显示右侧的边缘和中间内容,左侧边缘不展示
  • 情景2:导致loop为true状态下,页面只显示左侧的边缘和中间内容,右侧边缘不展示


    情景1
情景2

解决方案: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> 也会导致效果显示不出来

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容