Vue中使用vue-awesome-swiper实现移动端的轮播

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    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     }
原文地址:https://www.cnblogs.com/tian-long/p/8779742.html