TabBar.js 2.89 KB
// components/TabBar/TabBar.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabList: Array,
    activeIndex: {
      type: Number,
      observer: function (n) {
        if (this.data.tabIndex != n) {
          this.setTab(n, { suppressClick: true })
        }
      }
    },
    scroll: Boolean,
    /** 为 true 时 ready / page_show 触发的 setTab 不 emit click,避免子页首屏重复拉数 */
    suppressInitialClick: {
      type: Boolean,
      value: false
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    tabIndex: 0
  },
  lifetimes: {
    ready() {
      this.setTab(this.data.tabIndex, { suppressClick: this.data.suppressInitialClick })
      let that = this
      wx.$eventbus.on('page_show', n => {
        !that.data.width && that.setTab(that.data.tabIndex, { suppressClick: true })
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {

    change(e) {
      let {
        index
      } = e.currentTarget.dataset
      this.setTab(index)
    },
    /**
     * 切换内部 tab 下标并更新指示条样式。
     * @param {number} [index=0]
     * @param {{ suppressClick?: boolean }} [options] - suppressClick 为 true 时不 trigger click(首屏/ page_show 防重复拉数)
     */
    setTab(index = 0, options = {}) {
      const suppressClick = options.suppressClick === true
      let {
        tabIndex,
      } = this.data
      wx.$util.getViewInfo(`#tab-${tabIndex}`, old => {
        if (!old) {
          wx.$util.getViewInfo(`#tab-${index}`, res => {
            if (!res) return
            this.applyTabIndicator(index, res, suppressClick)
          }, this)
          return
        }
        let oldLeft = old.left
        let oldWidth = old.width
        wx.$util.getViewInfo(`#tab-${index}`, res => {
          if (!res) return
          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(--fontSize64);background-color:#347BFF;border-radius:3rpx;left:${readyLeft + readyWidth / 2}px;transition: all .1s;`
            })
          }
          this.applyTabIndicator(index, res, suppressClick)
        }, this)
      }, this)
    },
    /**
     * @param {number} index
     * @param {{ left: number, width: number }} res
     * @param {boolean} suppressClick
     */
    applyTabIndicator(index, res, suppressClick) {
      const { left, width } = res
      setTimeout(() => {
        this.setData({
          activeStyle: `width: var(--fontSize64);left:${left + (width - 32) / 2}px;background-color:#347BFF;`,
          tabIndex: index,
          to: `to-${index}`,
          width
        })
        if (!suppressClick) {
          this.triggerEvent('click', index)
        }
      }, 100)
    }
  }
})