官方文档 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>>