vue-awesome-swiper的正確使用姿勢

介紹一下vue-awesome-swiper最靠譜的使用方法。

目前網上對于vue-awesome-swiper的使用方法各種坑,要么版本對不上,要么swiper.css引用地址不對,要么swiper-pagination不顯示,要么自動輪播失效,反正各種坑讓人火大。下面介紹一下自己親測可用的正確使用方法。

首先版本,請使用3.1.3,別想著用什么4以上的或別的版本,目前就這個版本最穩定,不相信可以自己去測試,掉坑里可別怪沒提醒!

第一步:安裝

//直接安裝版本3即可,自動會選擇3.1.3版本
cnpm i vue-awesome-swiper@3 -S
//或者手動指定
cnpm i vue-awesome-swiper@3.1.3 -S

第二步:引入

頁面引入即可,沒必要全局引入,因為很少所以頁面都要使用輪播的。全局引入只會增加額外的加載緩存和加載速度。全部貼出來自己衡量吧。

頁面引入
請注意此處引入的swiper, swiperSlide的s是小寫,搞錯會報錯。

<script>
//頁面引入swiper
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
export default {
  components: {
    swiper,
    swiperSlide
  },
};
</script>

全局引入
main.js

import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
 
//引入樣式
import 'swiper/css/swiper.css'
 
Vue.use(VueAwesomeSwiper, /* { 全局組件的默認選項 } */)

第三步,頁面調用示例 —— 完整代碼

<template>
  <div class="app-container">
    <div class="swiper">
      <swiper ref="mySwiper" :options="swiperOptions">
        <swiper-slide
          v-for="item in 5"
          :key="item"
          :style="{backgroundImage: 'url('+require('@/assets/img/swiper-img.png')+')'}">
        </swiper-slide>
        <div class="swiper-pagination" slot="pagination"></div>
      </swiper>
    </div>
  </div>
</template>

<script>
//導入swiper
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
export default {
  name: 'default',
  data() {
    return {
      swiperOptions: {
        pagination: {
          el: '.swiper-pagination',    //與slot="pagination"處 class 一致
          clickable: true,            //輪播按鈕支持點擊
        }
      }
    };
  },
  components: {
    swiper,
    swiperSlide
  },
};
</script>

<style lang="scss" scoped>
.app-container{
  .swiper{
    width: 100%;
    
    &>>>.swiper-container {
      width: 100%;

      .swiper-slide {
        width: 100%;
        height: 0;
        padding-bottom: 28.1%;
        background-size: cover;
        background-position: center center;
        background-repeat: no-repeat;

        /* Center slide text vertically */
        display: -webkit-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        -webkit-justify-content: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        -webkit-align-items: center;
        align-items: center;
      }

      .swiper-pagination{
        .swiper-pagination-bullet-active{
          background-color: #F29B76;
        }
      }
    }
  }
}
</style>

第四步:配置options。

查看github的vue-awesome-swiper的官方示例:
https://v1.github.surmon.me/vue-awesome-swiper/

微信截圖_20210416110704.png

最終實現效果

示例圖

以上。

最新更新了“如何在nuxt項目里使用vue-awesome-swiper”的新文章,
有興趣的諸位可點擊查看:Nuxt使用vue-awesome-swiper的正確姿勢

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容