NavigationBar.js 2.25 KB
// components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    navStyle: String,
    custom: 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() {
      /**
       * 获取自定义导航栏信息。
       * 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
       *   statusBarHeight / screenWidth → getWindowInfo
       *   fontSizeSetting → getAppBaseInfo
       */
      const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
      const { height, right, width, top } = wx.getMenuButtonBoundingClientRect()
      let navigationBarHeight = height + (top - statusBarHeight) * 2 + 4 // 4
      let navigationBarPadding = screenWidth - right
      let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width) - width
      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()
      const currentPages = getCurrentPages()
      this.triggerEvent('navbarReady', {
        height: navHeight,
        statusBarHeight
      })
      this.setData({
        showNavBar: true
      })
      thisPage.setData({
        navHeight,
        statusBarHeight
      })
      if (currentPages.length == 1 && !thisPage.rootName)
        thisPage.setData({
          showHomeBtn: true
        })
    }
  },
  lifetimes: {
    attached() {
      this.init()
      this.setPageTitle()
    }
  }
})