index.js 1.78 KB
Component({
  properties: {
    // 导航栏标题
    title: {
      type: String,
      value: ''
    },
    // 背景颜色
    background: {
      type: String,
      value: 'transparent'
    },
    // 标题颜色
    color: {
      type: String,
      value: '#333333'
    },
    // 是否显示返回按钮
    showBack: {
      type: Boolean,
      value: true
    },
    // 返回按钮图标颜色
    backIconColor: {
      type: String,
      value: '#ffffff'
    },
    // 是否显示首页按钮
    showHome: {
      type: Boolean,
      value: false
    },
    // 特殊模式,不占高度
    noPlaceholder: {
      type: Boolean,
      value: false
    }
  },

  data: {
    statusBarHeight: 0,
    navBarHeight: 44,
    totalHeight: 0
  },

  lifetimes: {
    attached() {
      const app = getApp()

      // 直接使用 app.globalData 中已经计算好的数据
      this.setData({
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
        totalHeight: app.globalData.totalNavHeight
      })
    }
  },

  methods: {
    // 返回上一页
    onBack() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        // 如果是第一个页面,尝试返回首页
        wx.switchTab({
          url: '/pages/index/index',
          fail: () => {
            wx.reLaunch({
              url: '/pages/index/index'
            })
          }
        })
      }
      this.triggerEvent('back')
    },

    // 返回首页
    onHome() {
      wx.switchTab({
        url: '/pages/index/index',
        fail: () => {
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }
      })
      this.triggerEvent('home')
    }
  }
})