官方文檔 https://www.swiper.com.cn/
效果圖:
1、安裝
cnpm install swiper vue-awesome-swiper --save
2、引入
(1)全局在main.js中引入
import VueAwesomeSwiper from 'vue-awesome-swiper' import 'swiper/css/swiper.css' Vue.use(VueAwesomeSwiper)
(2)局部引入
import { Swiper, SwiperSlide } from 'vue-awesome-swiper' import 'swiper/css/swiper.css' export default { components: { Swiper, SwiperSlide } }
3、使用:
用到的API:
this.swiper.setTransition(1000);//設定過渡的時間
this.swiper.setTranslate(-1000);//設定位移,可以為正數
獲取某個點的寬高、位置:
this.$refs.item.getBoundingClientRect()
代碼:
<template> <div class="SegmentCell"> <a @click="stepActive=item" v-for="item in [6,8,12,20,10]" :key="item" class="m-l-r-20">{{item}}</a> <swiper class="swiper-container" ref="mySwiper" :options="swiperOptions"> <swiper-slide class="swiper-slide" :style="swiperStyle"> <div class="item t-a-c" v-for="item in stepActive" :ref="'item'+item" @click="setTranslate(item)">{{item}}</div> </swiper-slide> </swiper> </div> </template> <script> // 引入swiper滑動組件 import { Swiper, SwiperSlide } from 'vue-awesome-swiper' import 'swiper/css/swiper.css' export default { components: { Swiper, SwiperSlide }, data() { return { swiperStyle: {}, swiperOptions: { slidesPerView: 'auto', freeMode: true, // 隨意拖動位置 mousewheel: true }, stepActive: 6 } }, computed: { swiper() { return this.$refs.mySwiper.$swiper; } }, watch: { stepActive: { handler(newVal,oldVal) { console.log(this.stepActive); if(this.stepActive) { this.swiperStyle = "width:"+ 500*this.stepActive/16 + "rem"; // 動態設置寬度 } }, immediate: false } }, mounted() { }, destroyed() { this.swiper.destroy(false); }, methods: { setTranslate(index) { console.log(index,this.swiper.width,this.$refs["item"+index][0].getBoundingClientRect()) this.swiper.setTransition(1000);// 設定過渡的時間 this.swiper.setTranslate( 0 - 500*(index-1) + (this.swiper.width/2 - 500/2) );//設定位移,可以為正數 } } }; </script> <style lang="stylus" scoped> .SegmentCell { padding: 20px 0; border: solid 1px red; .swiper-container { .swiper-wrapper { transition: all 0.5s; } // 連接線 - 不跟隨內容滾動,放到.swiper-slide里面則跟隨內容滾動 &:before { content: ""; position: absolute; top: 28px; left: 0; width: 100%; height: 4px; background-color: red; opacity: 0.2; } .swiper-slide { width: 200%; height: 100px; .item { display: inline-block; width: 500px; color: red; } } } } </style>>