目录
  • 正文
    • Swiper 的参数
    • 代码实现
      • Error: Can‘t resolve ‘swiper/css/swiper.css‘ 如何解决
    • 其它方式

    正文

    Vue 或者 React 都可以使用 Swiper 来实现轮播图,并且可以满足大部分使用场景。

    在实现轮播图的过程踩了一些坑,并且由于 Vue2 和 Vue3 版本的差异,试了几种不同的写法,最终终于实现,轮播图的基础效果如下:

    Vue3使用Swiper实现轮播图示例详解

    Swiper 的参数

    • slidesPerView:每次显示几个轮播图
    • spaceBetween:每个轮播图之间的间距(单位:px)
    • loop:是否循环滚动
    • centeredSlides:是否居中对齐(true:居中,false:左对齐),默认 false 左对齐,
    • autoplay:是否自动播放
    • navigation:是否左右切换箭头
    • pagination:分页配置
      • clickable:在点击分页圆点的时候,是否进行切换
    • scrollbar:显示滚动条
      • draggable:滚动条可拖动
    • autoplay:切换图片的频率(毫秒为单位)
      • delay:切换的时间(单位:毫秒ms)
      • disableOnInteraction:滑动图片后不禁用自动播放 delay: 2500, disableOnInteraction: false,

    其他参数配置可参考官方 API:Swiper

    Vue3使用Swiper实现轮播图示例详解

    代码实现

    <template>
      <div class="swiperbox">
        <swiper
          :slidesPerView="1"
          :spaceBetween="30"
          :loop="true"
          :centeredSlides="true"
          :pagination="{ clickable: true}"
          :autoplay="{ delay: 2500, disableOnInteraction: false}"
          :navigation="true"
          :modules="modules"
        >
          <swiper-slide><img src="https://www.freexyz.cn/dev/@/assets/images/swiper1.png" alt="" /></swiper-slide>
          <swiper-slide><img src="https://www.freexyz.cn/dev/@/assets/images/swiper2.png" alt="" /></swiper-slide>
        </swiper>
      </div>
    </template>
    
    <script setup>
    import { Swiper, SwiperSlide } from 'swiper/vue' // swiper 所需组件
    import { Autoplay, Navigation, Pagination, A11y } from 'swiper'// 分页器
    // import 'swiper/swiper-bundle.css'
    import 'swiper/css'
    import 'swiper/css/navigation'
    import 'swiper/css/pagination'
    
    const modules = [Autoplay, Pagination, Navigation, A11y]
    </script>

    注:

    • 创建一个 modules 数组,目的是为了正常使用分页器和对应功能
    • 如果是 setup 钩子函数的写法,注意最后要 return 分页相关的配置。

    Vue3使用Swiper实现轮播图示例详解

    Error: Can‘t resolve ‘swiper/css/swiper.css‘ 如何解决

    解决方案: 在引入的文件中将其改为:import 'swiper/swiper-bundle.css'

    其它方式

    除了 Swiper ,还有一种更简便的方法,就是使用 ElementUI 或 Antd 的轮播图组件( Carousel 走马灯组件),可实现较为基础的需求。

    Vue3使用Swiper实现轮播图示例详解

    以上就是Vue3使用Swiper实现轮播图示例详解的详细内容,更多关于Vue3 Swiper轮播图的资料请关注其它相关文章!

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。