1.获取设备信息及胶囊按钮信息:
App({
globalData: {
navHeight:”,
statusBarHeight:”,
menuButtonHeight:”,
windowHeight:”
},
onLaunch: function () {
// 获取全局数据节点
const that=this.globalData
// 获取右侧胶囊按钮信息 bottom,height,left,right,top,width
const menuButtonInfo=wx.getMenuButtonBoundingClientRect();
// 获取设备基础信息
wx.getSystemInfo({
complete: ({statusBarHeight,windowHeight,windowWidth}) => {
console.log(windowHeight,windowWidth)
// 设置导航栏高度
that.navHeight=statusBarHeight+menuButtonInfo.height+(menuButtonInfo.top-statusBarHeight)*2;
// 获取胶囊按钮距离顶部的距离
that.statusBarHeight=statusBarHeight;
// 设置设备高度
that.windowHeight=windowHeight;
},
})
}
})
2.创建组件:
/**navBar.js**/
const App = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
pageName: String, //中间的title
showNav: { //判断是否显示左上角的按钮
type: Boolean,
value: true
},
showHome: { //判断是否显示左上角的home按钮
type: Boolean,
value: true
}
},
/**
* 组件的初始数据
*/
data: {
showNav: true, //判断是否显示左上角的home按钮
showHome: true, //判断是否显示左上角的按钮
},
lifetimes: {
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () {
this.setData({
navHeight: App.globalData.navHeight,
statusBarHeight: App.globalData.statusBarHeight
})
}
},
/**
* 组件的方法列表
*/
methods: {
//回退
navBack: function () {
if(this.data.showNav){
wx.navigateBack();
return;
}
wx.navigateTo({
url: ‘/pages/index/index’
})
},
}
})
/**navBar.wxml**/
<view class=”navbar” style=”height:{
{navHeight}}px;padding:{
{statusBarHeight}}px 0 0″>
<text bindtap=”navBack” wx:if=”{
{showNav}}” class=”back” style=”height:{
{navHeight}}px;padding:{
{statusBarHeight}}px 0 0 10px”>返回</text>
<text class=”title”>{
{pageName}}</text>
</view>
/**navBar.wxss**/
.navbar {
width: 100%;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
z-index: 10;
flex-shrink: 0;
background: #000;
display: flex;
justify-content: center;
align-items: center;
}
.title{
font-size: 40rpx;
color: #fff;
}
.back{
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
}
/**navBar.json**/
{
“component”:true
}
3.应用组件
/**index.json*/
{
“usingComponents”: {
“navbar”:”/components/navBar/navBar”
}
}
/**index.html*/
<!–index.wxml–>
<view class=”container”>
<navbar page-name=”首页” show-nav=”{
{false}}” show-home=”{
{false}}”></navbar>
<view class=”userinfo”>
<button wx:if=”{
{!hasUserInfo && canIUse}}” open-type=”getUserInfo” bindgetuserinfo=”getUserInfo”> 获取头像昵称 </button>
<block wx:else>
<image bindtap=”bindViewTap” class=”userinfo-avatar” src=”{
{userInfo.avatarUrl}}” mode=”cover”></image>
<text class=”userinfo-nickname”>{
{userInfo.nickName}}</text>
</block>
</view>
<view class=”usermotto” bindtap=”goPage”>
<text class=”user-motto”>{
{motto}}</text>
</view>
</view>
/**********************如果本案例对你有用记得点个赞************************/