swiper,一款不錯的輪播插件,支持移動端 官網api網址: http://www.swiper.com.cn/api/index.html
在vue中使用swiper, 有專門的一個npm包: vue-awesome-swiper
使用步驟:
1.安裝vue版swiper
cnpm i -S vue-awesome-swiper
2. 在.vue組件中引入swiper , swiperSlide 和 css樣式
1 import {swiper, swiperSlide} from 'vue-awesome-swiper' 2 import 'swiper/dist/css/swiper.css' //注意這里
3.編寫布局和樣式
1 <div class="swiper-box"> 2 <swiper class="box-container" :options="swiperOption" ref="mySwiper"> 3 <swiper-slide v-for="(item, index) in imgLists" :key="index" @touchmove.native="stopPlay" @touchend.native="play"> // 自定義組件要加上.native 4 <img class="swiper-image" :src="item.url" alt=""> 5 </swiper-slide> 6 7 <div class="swiper-pagination" slot="pagination"></div> 8 <div class="swiper-button-prev swiper-button-white" slot="button-prev"></div> 9 <div class="swiper-button-next swiper-button-white" slot="button-next"></div> 10 <div class="swiper-scrollbar" slot="scrollbar"></div> 11 </swiper> 12 </div>
1 .swiper-image{ 2 width: 100%; 3 height: 270px; 4 }
4.在data里配置imgLists圖片地址和配置swiperOption參數
1 imgLists: [ 2 { 3 url: "/src/static/img1.jpg" 4 }, 5 { 6 url: "/src/static/img2.jpg" 7 }, 8 { 9 url: "/src/static/img3.jpg" 10 }, 11 { 12 url: "/src/static/img4.jpg" 13 } 14 ], 15 swiperOption: { 16 notNextTick: true, 17 autoplay: { // 自動播放 18 delay: 3000, 19 stopOnLastSlide: false, 20 disableOnInteraction: false 21 }, 22 loop: true, // 循環 23 directionType: "horizontal", // 方向 24 pagination: { // 分頁器 25 el: '.swiper-pagination', 26 type: "bullets", 27 clickable :true 28 }, 29 navigation: { // 左右按鈕 30 nextEl: '.swiper-button-next', 31 prevEl: '.swiper-button-prev' 32 }, 33 observer:true, // 啟動動態檢查器(OB/觀眾/觀看者),當改變swiper的樣式(例如隱藏/顯示)或者修改swiper的子元素時,自動初始化swiper。 34 observeParents: true, // 將observe應用於Swiper的父元素。當Swiper的父元素變化時,例如window.resize,Swiper更新。 35 setWrapperSize :true // Swiper使用flexbox布局(display: flex), 36 // 開啟這個設定會在Wrapper上添加等於slides相加的寬或高,在對flexbox布局的支持不是很好的瀏覽器中可能需要用到。 37 }
5. 在computed中
1 computed: { 2 mySwiper() { 3 return this.$refs.mySwiper.swiper; 4 } 5 },
6.在methods中,
1 stopPlay() { 2 this.mySwiper.autoplay.stop(); // 當手指觸摸時停止自動播放 3 }, 4 play() { 5 this.mySwiper.autoplay.start(); // 當手指離開時開始自動播放 6 }