首先项目里创建一个navbar组件, 这里面用到的点有:
- uniapp组件没有页面级生命周期,于是直接用vue的生命周期
- 动态绑定style,用定位控制头部导航栏组件距离手机顶部的高度为设备状态栏的高度。
- 因为是做微信小程序,得考虑胶囊按钮的高度,以及胶囊按钮到状态栏的高度。
- 文字字体颜色图标动态传值控制切换。
- 在调试过程中,浏览器会报错,于是使用,#idenif #endif控制代码执行。
头部导航栏组件代码如下:
<template>
<view @click="back" :style="{top:statusBarHeight + 'px',height:(cachetHeight + smallHeight)+'px',lineHeight:(cachetHeight + smallHeight)+'px'}" class="navbar">
<image v-if="blackArrow" style="height: 50rpx;width: 50rpx;margin: 0 20rpx;" src="../../static/left-arrow.png"></image>
<image v-if="!blackArrow" style="height: 50rpx;width: 50rpx;margin: 0 20rpx;" src="../../static/left-arrow-black.png"></image>
<view :style="{color:color}" class="title">{{title}}</view>
</view>
</template>
<script>
export default {
data() {
return {
statusBarHeight:0, //手机状态栏的高度
cachetHeight:0, //胶囊按钮高度
smallHeight:0 //苹果8px,安卓6px 胶囊按钮到手机状态栏的间距。,
}
},
props: {
title: {
required: true,
default: ''
},
color:{
default:'#fff'
},
blackArrow:{
default:false
}
},
methods:{
back(){
uni.navigateBack({
delta:1
})
}
},
created(){
// #ifndef H5 || APP-PLUS || MP-ALIPAY
// 状态栏高度,单位:rpx
this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight; //获取状态栏的高度
this.cachetHeight = uni.getMenuButtonBoundingClientRect().height //获取胶囊按钮的高度
console.log('statusBarHeight'+this.statusBarHeight);
console.log('cachetHeight'+this.cachetHeight);
if(uni.getSystemInfoSync().platform =='devtools' || 'ios'){
//判断设备
this.smallHeight = 8
}
if(uni.getSystemInfoSync().platform =='android'){
this.smallHeight = 6
}
// #endif
}
}
</script>
<style scoped>
.navbar {
display: flex;
color: #000;
align-items: center;
position: absolute;
width: 100%;
z-index: 100;
}
.title {
color: #fff;
font-size: 36rpx;
}
</style>
使用效果:
使用页面代码如下(因为头部导航栏组件用了定位,你可以自己定义头部的背景样式)
<view class="order-allocation"> //此为根目录
<view class="top">
<navbar title="订单分配" :blackArrow="true">
</navbar>
<view class="light-circle"></view>
<view class="light-circle-right"></view>
</view>
</view>
.top {
background: linear-gradient(to bottom, #FF2C2E, #FC615F);
position: relative;
overflow: hidden;
height: 11vh;
}
白底黑字:
<template>
<view class="install-detail"> //此为根目录
<view class="top">
<navbar color="#000" title="安装详情">
</navbar>
</view>
.top {
background: #fff;
position: relative;
overflow: hidden;
height: 11vh;
color: #000;
}