vue调用swiper的那些巨坑,这里大概率有你想要的解决方案

1,213 阅读1分钟

基本使用

安装

npm install swiper --save

调用

全局

import Swiper from 'vue-awesome-swiper';//引入组件
import 'swiper/dist/css/swiper.css';//引入样式
Vue.use(Swiper);//挂载实例

局部单组件

import { swiper, swiperSlide } from "vue-awesome-swiper"; 
import "swiper/dist/css/swiper.css"; components: { swiper, swiperSlide }

template

<swiper :options="swiperOption" class="swiper-wrap"  ref="mySwiper" v-if="banners.length!=0">
    <swiper-slide v-for="(item,index) in banners" :key="index" >
      <img :src="item.pic" alt="" />
    </swiper-slide>
</swiper>

data

data() {
    const that = this;
    return {
      imgIndex: 1,
      swiperOption: {
        //循环
        loop: true,
        //设定初始化时slide的索引
        initialSlide: 0,
        //自动播放
        autoplay: {
          delay: 1500,
          stopOnLastSlide: false,
          /* 触摸滑动后是否继续轮播 */
          disableOnInteraction: false
        },
        //滑动速度
        speed: 800,
        //滑动方向
        direction: "horizontal",
        //分页器设置
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
          type: "bullets"
        }
      }
   };
},

具体实现效果参考swiper官网的Api文档自行设置

这些坑你得知道

情况一:报错如下

Snipaste_2021-08-30_22-30-08.png

这个极大可能是因为版本太新导致的问题,只需将版本降一下级

解决方案

npm uninstall vue-awesome-swiper
npm install vue-awesome-swiper@3.1.3  --save-dev

情况二:报错如下

Snipaste_2021-08-30_22-53-43.png

还是因为版本的一些问题,需要注意不同版本对应的swiper,swiperSlide的第一个S的大小写问题

解决方案

查看vue-awesome-swiper的版本信息

若是3.x 版本的 -- 引入模块时使用小写
import { swiper, swiperSlide } from “vue-awesome-swiper”;
若是4.x 版本的 -- 引入模块时使用大写
import { Swiper, SwiperSlide } from “vue-awesome-swiper”;

情况三:图片不局中

Snipaste_2021-08-31_17-36-59.png

解决方案:

按道理来说只要添加centeredSlides : true,即可。若没有生效,就需给 swiper-slide 设置 text-align: center; 的样式