vue + swiper 实现今日头条触摸滑动tab栏

2018-07-09  本文已影响0人  _conquer_

1、引入swiper.js
2、html结构为

<div id="topNav" class="swiper-container">
    <div class="swiper-wrapper">
         <div class="swiper-slide" v-for="(item,index) in depList" :class="{active:dep_id==item.department_id}">
            <span>{{item.department_name}}</span>  
         </div>
     </div>
</div>

3、定义变量

export default{
        name:"find_doc",
        data(){
            return {
                mySwiper:false,
                swiperWidth:'',
                maxTranslate:'',
                maxWidth:'',
                depList:[
                          {department_id: 1, department_name: "内科"},
                          {department_id: 5, department_name: "外科"}
                         ] ,
            }
        },

4、具体代码

   mounted(){
       var that = this;
       that.mySwiper = new Swiper('#topNav', {
                       freeMode: true,
                       freeModeMomentumRatio: 0.5,
                       slidesPerView: 'auto',
                       resistanceRatio:0.7,
                   });
                   that.swiperWidth =that.mySwiper.container['0'].clientWidth;
                   that.maxTranslate = that.mySwiper.maxTranslate();
                   that.maxWidth = -that.maxTranslate + that.swiperWidth / 2
                   that.mySwiper.on('tap', function(swiper, e) {
                       //swiper.clickedIndex(获取到当前点击的索引)
                       if(that.dep_id==that.depList[swiper.clickedIndex].department_id){
                           return;
                       }
                       that.loading_show=true;
                       that.dep_name=that.depList[swiper.clickedIndex].department_name;
                       that.dep_id=that.depList[swiper.clickedIndex].department_id;
                       var slide,slideLeft,slideWidth,slideCenter,nowTlanslate;
                       slide = swiper.slides[swiper.clickedIndex]
                       slideLeft = slide.offsetLeft
                       slideWidth = slide.clientWidth
                       slideCenter = slideLeft + slideWidth / 2
                       that.mySwiper.setWrapperTransition(300)
                       if (slideCenter < that.swiperWidth / 2) {
                           that.mySwiper.setWrapperTranslate(0)
                   
                       } else if (slideCenter > that.maxWidth) {
                           that.mySwiper.setWrapperTranslate(that.maxTranslate)
                   
                       } else {
                           nowTlanslate = slideCenter - that.swiperWidth / 2
                           that.mySwiper.setWrapperTranslate(-nowTlanslate)                    
                       }
     }

效果见:http://www.17sucai.com/preview/702590/2017-06-08/toutiaoNav/index.html

上一篇下一篇

猜你喜欢

热点阅读