百度找的适用于 Vue 的轮播组件
安装
cnpm i vue-awesome-swiper --save
引入
-
全局引入
在main.js中引入import Vue from 'vue' import VueAwesomeSwiper from 'vue-awesome-swiper' import 'swiper/dist/css/swiper.css' Vue.use(VueAwesomeSwiper)
-
组件引入
// 样式记得要导入 import 'swiper/dist/css/swiper.css' import { swiper, swiperSlide } from 'vue-awesome-swiper' export default { components: { swiper, swiperSlide } }
使用
我是组件引入,就只写这一种使用
<template>
<div>
<!-- 加入判断时,loop才生效 -->
<swiper :options="swiperOption" ref="mySwiper" v-if="homeSwiper.length > 1" >
<swiper-slide v-for="item in homeSwiper" :key="item.image"
><a :href="item.link"
><img :src="item.image" alt="" class="swiper-img"/></a
></swiper-slide>
<div
id="home-pagination"
slot="pagination"
class="swiper-pagination"
></div>
</swiper>
</div>
</template>
<script>
import { swiper, swiperSlide } from "vue-awesome-swiper";
import "swiper/dist/css/swiper.css";
export default {
name: "HomeSwiper",
components: {
swiper,
swiperSlide
},
props:{
homeSwiper:{
type:Array,
default(){
return []
}
}
},
data() {
return {
swiperOption: {// 轮播图配置,参数同swiper官方api参数
slidesPerView: 1, // wrapper中显示的图片数量
speed: 500, // 图片切换速度
pagination: { // 分页器
el: "#home-pagination"
},
loop: true, // 循环播放
notNextTick: true,
preloadImages: false,
on: {
touchEnd: function(event) {
//你的事件
}
}
}
};
},
computed: {},
mounted() {
// 只有一张图时,autoplay为false
this.swiperOption.autoplay =
this.homeSwiper.length != 1
? {
delay: 4000,
stopOnLastSlide: false,
disableOnInteraction: false
}
: false;
}
};
</script>
<style scoped>
.swiper-img {
width: 100%;
height: 100%;
}
</style>
留意与总结
当时配置的时候还是有点小坑:
-
必须导入css
import 'swiper/dist/css/swiper.css'
-
设置loop循环播放时,要给swiper标签加上v-if判断才生效
<swiper :options="swiperOption" v-if="homeSwiper.length > 1" > </swiper>
这个方法也是找了很久才找到,我试了确实有效,但是不明白原理。
-
autoplay自动播放轮播图,判断当只有一个图时,就不必播放
-
另外一点时当用户与轮播图进行交互时(比如滑动),默认轮播图就不再播放了,要想继续播放,需设置
autoplay:{ disableOnInteraction: false //用户操作swiper之后自动切换不会停止 }
-
安装的vue-awesome-swiper是3.x版本的,配置选项跟swiper官网配置选项一致,注意是看4和5版本的swiper。
另外附上swiper中文文档
swiper中文网