vue——手写swiper子组件,pagination不显示、轮播无效问题解决
效果:
index.html:
<link href="https://cdn.bootcss.com/Swiper/3.4.2/css/swiper.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/Swiper/3.4.2/js/swiper.min.js"></script>
注意:我使用的vue版本是2.5.2
Detail父组件:
<template> <div id="detail"> <DetailSwiper v-bind:swiperList="swiperList"></DetailSwiper> </div> </template> <script> import DetailSwiper from '../components/DetailSwiper.vue' export default { name: 'Detail', data() { return {
swiperList:[]
} },
mounted(){
var _this = this;
***** //获取轮播图片
_this.swiperList = list;//list为后端返回的轮播图数据
}, components: { DetailSwiper } } </script> <style scoped> #detail{ width:100%; overflow:hidden;//一定要加,否则轮播图会超出横向屏幕形成滚动条 } </style>
DetailSwiper子组件:
<template> <div class="shopImgDiv"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide" v-for="item in swiperList"> <img :src="item.imgpath" style="width:100%;height:100%"> </div> </div> <div class="swiper-pagination"></div> </div> </div> </template> <script> export default { name: 'DetailSwiper', data() { return { swiperLength: 0, swiperList: [], option: { autoplay: false, loop: false, pagination: '', } } }, methods: { initSwiper: function() { let _this = this; var mySwiper = new Swiper(".swiper-container", { autoplay: _this.option.autoplay, loop: _this.option.loop, autoplayDisableOnInteraction: false,//用户操作swiper之后,是否禁止autoplay preventLinksPropagation: false,//是否阻止click冒泡。拖动Swiper时阻止click事件 pagination: _this.option.pagination,//是否显示小圆点 observer: true, //修改swiper自己或子元素时,自动初始化swiper observeParents: true, //修改swiper的父元素时,自动初始化swiper }) } }, props: ['swiperList'], watch: { swiperList: function(newVal, oldVal) { var _this = this; var len = newVal.length; if (len == 1) { //图片只有一张时不轮播 _this.$nextTick(() => { //解决动态获取图片后,不轮播或轮播到最后一张后,第一张一闪而过的问题 _this.option.autoplay = false; _this.option.loop = false; _this.option.pagination = ''; _this.initSwiper(); }) } else if(len > 1) { _this.$nextTick(() => { _this.option.autoplay = 3000; _this.option.loop = true; _this.option.pagination = '.swiper-pagination'; _this.initSwiper(); }) } } } } </script> <style @scoped> @import '.././assets/css/components/componentSwiper.css'; </style>
componentSwiper.css:
body { margin: 0; padding: 0; } .swiper-container { width: 100%; height: 100%; } .shopImgDiv { width: 100%; overflow: hidden; height: 100%; //可以设置为auto,会根据图片的高度进行调整 position: relative;
backgound:lightcoral; } .swiper-wrapper { font-size: 0; } .swiper-pagination { width: 100%; height: .2rem; text-align: center; position: absolute; bottom: 0 !important; line-height: .2rem; box-sizing: border-box; padding: 0 .3rem; font-size: 0; z-index: 1; } .swiper-pagination-bullet { background-color: rgba(255, 255, 255, 1); opacity: 1; } .swiper-pagination-bullet-active { //设置小圆点激活颜色 background-color: #ff7035 !important; opacity: 1; } .swiper-container-autoheight, .swiper-container-autoheight .swiper-slide { font-size: 0; position: relative; }