NavigationBar.js 2.59 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.p.router.getPageInstance()
      if (thisPage) thisPage.navigationBarTitleText = this.title
    },
    init() {
      /**
       * 获取自定义导航栏信息。
       * 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
       *   statusBarHeight / screenWidth → wx.getWindowInfo()
       *   fontSizeSetting → wx.getAppBaseInfo()
       * 新接口均为同步返回,去掉原来的 .then 异步时序。
       */
      const windowInfo = wx.getWindowInfo() || {}
      const appBaseInfo = wx.getAppBaseInfo() || {}
      let {
        fontSizeSetting,
        statusBarHeight,
        screenWidth,
      } = {
        ...windowInfo,
        fontSizeSetting: appBaseInfo.fontSizeSetting,
      }
      const {
        height,
        right,
        width,
        top,
      } = wx.getMenuButtonBoundingClientRect()
      const currentPages = getCurrentPages()
      const { 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.p.router.getPageInstance()
      this.triggerEvent('navbarReady', {
        height: navHeight,
        statusBarHeight
      })
      this.setData({
        showNavBar: true
      })
      thisPage.setData({
        navHeight,
        statusBarHeight
      })
    },
    back() {
      wx.p.router.back()
    }
  },
  lifetimes: {
    attached() {
      this.init()
      this.setPageTitle()
    }
  }
})