小程序自定义头部组件

1.新建文件navbar

小程序自定义头部组件_第1张图片

2.index.wxml


    
  
      {{navbarData.name}}
  

  
   
    
      
        
      
    
  


小程序自定义头部组件_第2张图片

wxss

/* 顶部要固定定位   标题要居中   自定义按钮和标题要和右边微信原生的胶囊上下对齐 */
.nav-wrap {
  position: fixed;
  width: 100%;
  top: 0;
  background: #fff;
  color: #000;
  z-index: 9999999;
  /* background: transparent */
}
/* 标题要居中 */
.nav-title {
  position: absolute;
  text-align: center;
  max-width: 330rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  font-size: 36rpx;
  color: #2c2b2b;
  font-weight: 600;
}
.nav-capsule {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}
.back-pre {
  width: 52rpx;
  height: 52rpx;
  margin-top: 4rpx;
  padding: 10rpx;
}
.nav-capsule {
   display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}


js

const app = getApp()
Component({
  properties: {
    navbarData: {   //navbarData   由父页面传递的数据
      type: Object,
      value: {},
      height: app.globalData.height
    }
  },
  data: {
    height: '',
    //默认值  默认显示左上角
    navbarData: {
    }
  },
  attached: function () {
    // 定义导航栏的高度   方便对齐
    this.setData({
      height: app.globalData.height
    })
  },
  created() {
    this.setData({
      height: app.globalData.height
    })
  },
  methods: {
    // 返回上一页面
    _navback() {
      wx.navigateBack()
    }
  }
}) 

3.使用

1.app.json添加

	"navigationStyle": "custom"

小程序自定义头部组件_第3张图片
2.app.js 获取不同设备的高度

App({
  onLaunch: function () {
    //获取设备顶部窗口的高度(不同设备窗口高度不一样,根据这个来设置自定义导航栏的高度
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.height = res.statusBarHeight
      }
    })
  },
  globalData:{
    height: 0
  }
})

3.在页面中使用组件
*页面json引入组件

{
  "usingComponents": {
    "nav-bar" : "../index/index"
  }
}

*页面使用



		....内容

*页面js

Page({
  data: {
  	height: app.globalData.height * 2 + 25,
    navbarData:{
      name: '我是标题'
    }
  },
  onLoad: function (options) {

  },
})

小程序自定义头部组件_第4张图片

你可能感兴趣的:(小程序自定义头部组件)