效果:
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; }