TabBar.js 2.09 KB
// components/TabBar/TabBar.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabList: Array,
    activeIndex: {
      type: Number,
      observer: function (n) {
        console.log(this.data.tabIndex, 'activeIndex', n);
        console.log(this.data.tabIndex != n);
        if (this.data.tabIndex != n) {

          this.setData({
            tabIndex: this.data.activeIndex
          })
          this.setTab(this.data.tabIndex)
        }
      }
    },
    scroll: Boolean
  },
  /**
   * 组件的初始数据
   */
  data: {
    tabIndex: 0
  },
  lifetimes: {
    ready() {
      // console.log('lifetimes',this.data.tabIndex);
      // console.log('lifetimes',this.data.activeIndex);
      this.setTab(this.data.tabIndex)
      let that = this
      wx.$eventbus.on('page_show', n => {
        !that.data.width && that.setTab(that.data.tabIndex)
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {

    change(e) {
      let {
        index
      } = e.currentTarget.dataset
      this.setTab(index)
    },
    setTab(index = 0) {
      let {
        tabIndex,
      } = this.data
      wx.$util.getViewInfo(`#tab-${tabIndex}`, old => {
        let oldLeft = old.left
        let oldWidth = old.width
        wx.$util.getViewInfo(`#tab-${index}`, res => {
          let {
            left,
            width
          } = res
          if (tabIndex != index) {
            let readyLeft = oldLeft > left ? left : oldLeft
            let readyWidth = oldLeft > left ? oldLeft - left : left - oldLeft
            this.setData({
              activeStyle: `width: var(--fontSize36);background-color:#2C66F7;border-radius:3rpx;left:${readyLeft + readyWidth / 2}px;transition: all .1s;`
            })
          }
          setTimeout(() => {
            this.setData({
              activeStyle: `width: var(--fontSize64);left:${left + (width - 32) / 2}px;background-color:#2C66F7;`,
              tabIndex: index,
              to: `to-${index}`,
              width
            })
            this.triggerEvent('click', index)
          }, 100)
        }, this)
      }, this)
    }
  }
})