NavigationBar.js 2.24 KB
// components/navigationBar/navigationBar.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    navStyle: String,
    custom: Boolean,
    showBack: Boolean,
    pageTitle: {
      type: String,
      value: '',
      observer(n) {
        if (n) {
          this.title = n
          this.setPageTitle()
        }
      }
    }
  },
  title: '',
  /**
   * 组件的初始数据
   */
  data: {},

  /**
   * 组件的方法列表
   */
  methods: {
    setPageTitle() {
      let thisPage = wx.$router.getPageInstance()
      if (thisPage) thisPage.navigationBarTitleText = this.title
    },
    init() {
      /**
       * 获取自定义导航栏信息
       */
      wx.getSystemInfo().then(res => {
        let {
          fontSizeSetting,
          statusBarHeight,
          screenWidth
        } = res
        const {
          height,
          right,
          width,
          top
        } = wx.getMenuButtonBoundingClientRect(),
          currentPages = getCurrentPages(), {
            showBack
          } = this.data
        if (showBack && currentPages.length > 1) this.setData({
          SHOWBACK: true
        })
        let navigationBarHeight = height + ((top - statusBarHeight) * 2)
        let navigationBarPadding = screenWidth - right
        let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
        this.setData({
          statusBarHeight,
          navigationBarHeight,
          navigationBarStyle: `font-size:${fontSizeSetting}px;`,
          navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
        })
        this.emit({
          navigationBarHeight,
          statusBarHeight
        })
      })
    },
    emit({
      navigationBarHeight,
      statusBarHeight
    }) {
      let navHeight = navigationBarHeight + statusBarHeight
      const thisPage = wx.$router.getPageInstance()
      this.triggerEvent('navbarReady', {
        height: navHeight,
        statusBarHeight
      })
      this.setData({
        showNavBar: true
      })
      thisPage.setData({
        navHeight,
        statusBarHeight
      })
    },
    back() {
      wx.$router.back()
    }
  },
  lifetimes: {
    attached() {
      this.init()
      this.setPageTitle()
    }
  }
})