如果我们需要给标题加上按钮,图片,复杂的样式的时候,系统的标题就不能满足我们的要求了,这时我们需要自定义标题:
1.在定义的页面路径的page.json中实现如下代码:
{
"path": "pages/index/index",
"style": {
"navigationStyle": "custom" //自定义标题要使用custom
}
},
2.自定义组件,在components文件夹下面,定义一个customTitle.vue页面,写入如下代码:要注意小程序的顶部是由:状态栏+标题栏组成的。
<template>
<view class="nav-box">
<view class="nav-top-one" @click="backpage" :style="{lineHeight:toBar + 'px',marginTop:statusBarHeight+'px'}">
<img src="@/static/images/position.png" class="nav-top-left">
<view>{{titleName}}</view>
</view>
</view>
</template>
<script>
export default {
name: "qx-topBar",
props: {
titleName: {
type: String,
}
},
data() {
return {
statusBarHeight:'',//状态栏的高度
toBar:'',//标题栏的高度
};
},
onReady() {
this.getPhoneHeight();
},
methods: {
getPhoneHeight() { //获取高度
let that = this;
uni.getSystemInfo({
success: function(res) {
if (res.platform == "ios") {
that.toBar = 44;
} else if (res.platform == "android") {
that.toBar = 48;
} else {
that.toBar = 44;
}
that.statusBarHeight = res.statusBarHeight;//状态栏的高度
},
});
},
backpage() {
// 跳转页面
wx.navigateTo({
url: "/pages/index/webView"
});
},
},
};
</script>
<style scoped>
.nav-box {
padding-left: 16rpx;
}
.nav-top-one {
display: flex;
align-items: center;
}
.nav-top-left {
height: 36rpx;
width: 36rpx;
}
</style>
3.使用:取消原生导航栏后,由于窗体为沉浸式,占据了状态栏位置。此时可以使用一个高度为 状态栏+标题栏的高度组成的 view 放在页面顶部,避免页面内容出现在状态栏。
<template>
<view class="sweepstakes">
<qx-topBar class="topbar" :titleName="title"></qx-topBar>
</view>
//当头部固定时,设置页面内容具体顶部的距离为状态栏+标题栏的高度
<view :style="{marginTop:phoneHeight+'px'}">
</view>
</template>
<script>
import qxTopBar from '../../components/customTitle.vue'
export default {
components: {
qxTopBar
},
data(){
return {
title:'',//自定义标题的名称,
phoneHeight:''
}
},
onLoad: function(options) {
let that = this;
let toBar = '' ;
uni.getSystemInfo({
success: function(res) {
if (res.platform == "ios") {
toBar = 44;
} else if (res.platform == "android") {
toBar = 48;
} else {
toBar = 44;
}
that.phoneHeight = res.statusBarHeight + toBar;
},
});
},
}
</script>
<style>
//设置头部固定
.sweepstakes {
width: 100vw;
position: fixed;
z-index: 9999;
background-color: #EEEEEE;
top: 0;
left: 0;
.topbar {
width: 100%;
}
}
</style>
实现的最终效果如下图所示: