美文网首页
微信小程序:一个好用的tab组件~

微信小程序:一个好用的tab组件~

作者: yangSmallXing | 来源:发表于2018-12-17 11:23 被阅读0次
GIF.gif

不说废话,直接上代码,具体实现可以研读代码,代码量不多的。

WXML

<view class='container'>
<scroll-view class="tab" scroll-x scroll-left="{{tabScroll}}" scroll-with-animation="true">
 <block wx:for="{{menuList}}" wx:key="index">
  <view class="tab-item " style="width:{{100/count}}%" data-current="{{index}}" bindtap='clickMenu'>
  <view class="item {{currentTab == index ? 'active' : ''}}">
  {{item.name}}
  </view>
  </view>
 </block>
 </scroll-view>
 </view>

WXSS

.container{
 width: 100%;
 height: 79rpx;
 background: #FCFCFC;
}
.tab{
 width: 100%;
 height: 79rpx;
 position: fixed;
 top: 0;
 left: 0;
 z-index: 100;
 white-space: nowrap;
 box-sizing: border-box;
 overflow: hidden;
 line-height: 78rpx;
 background: #FCFCFC;
}
.tab-item{
 font-family: SourceHanSansCN-Normal;
 display: inline-block;
 width: 25%;
 font-size: 30rpx;
 color: #666666;

}

.item{
 width:fit-content;
 font-family: SourceHanSansCN-Normal;
 margin: auto;
 font-size: 30rpx;
 color: #666666;
 height: 70rpx;
}

.active{
 color: #4A5FE2;
  border-bottom: 1rpx solid #4A5FE2;
}

JS

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    menuList:Array,
    currentTab:Number,
    windowWidth: Number,
    tabScroll: Number,
    count: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
  
  },

  /**
   * 组件的方法列表
   */
  methods: {
    clickMenu:function(event){
      var res = wx.getSystemInfoSync()
      this.properties.windowWidth =  res.windowWidth
      var current = event.currentTarget.dataset.current
      var tabWidth = this.properties.windowWidth / this.properties.count
      this.setData({
        tabScroll: (current - this.properties.count/2) * tabWidth
        })
    if(this.properties.currentTab == current) {
        return false
    } else {
     this.setData({
       currentTab: event.currentTarget.dataset.current
     })
     this.triggerEvent('clickMenu', { current: event.currentTarget.dataset.current },{})
    }
    },
  
  }
})

在page使用

"usingComponents": {
  "tab": "../components/tab/index"
}
<tab menuList="{{menuList}}" bind:clickMenu="clickMenu" count="6" />

相关文章

网友评论

      本文标题:微信小程序:一个好用的tab组件~

      本文链接:https://www.haomeiwen.com/subject/cnsqkqtx.html