vue3 使用Swiper 8,添加图片懒加载

1,002 阅读1分钟

写在前面

大家好,我是江枫眠,在前端行业摸排滚打好多年,欠过技术债,也还过技术债,不管前端还能做几年,励志写可维护的前端代码

进入主题

使用方法和以往版本,大同小异,文档实属难读了些,想要使用什么功能或者模块,还得看官网给的demo,查看源码,多读几遍API,多看几个demo,会发现使用起来越发的得心应手。添加图片懒加载也很简单,引入Lazy模块,引入相关的css,添加一个loading 模块,这个loading可以改变颜色,默认的是蓝色,查看其css可以看到有黑色和白色两种样式 swiper-lazy-preloader-whiteswiper-lazy-preloader-black

上代码

swiper.vue

<template>
  <div>
    <div class="swiper">
      <swiper class="img-swiper" :slides-per-view="4" :slides-per-group="4" :space-between="30" :scrollbar="{ draggable: true }" navigation :lazy="true">
        <swiper-slide v-for="(item, index) in swiperData" :key="index">
          <div class="swiper-item">
            <img :data-src="item.imgUrl" class="swiper-lazy"/>
            <div class="swiper-lazy-preloader"></div>
            <div class="des">{{ item.deviceInfo }}</div>
          </div>
        </swiper-slide>
      </swiper>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import SwiperCore, { Navigation, Pagination, Scrollbar, Autoplay, Lazy } from 'swiper'

import { Swiper, SwiperSlide } from 'swiper/vue'
SwiperCore.use([Pagination, Autoplay, Navigation, Scrollbar, Lazy])
import 'swiper/less'
import 'swiper/less/lazy'
import 'swiper/less/navigation'
import 'swiper/less/pagination'

</script>
<style lang="less"></style>

Swiper官方文档