uniapp 微信小程序自己封装头部标题栏

2023-02-14,,,,

一、首先要关闭原生导航栏 :在pages.json 中设置  "navigationStyle":"custom"

二、在APP.vue中

onLaunch: function() {
uni.getSystemInfo({
success: function(e) {
// #ifndef MP
Vue.prototype.StatusBar = e.statusBarHeight;
if (e.platform == 'android') {
Vue.prototype.CustomBar = e.statusBarHeight + 50;
} else {
Vue.prototype.CustomBar = e.statusBarHeight + 45;
};
// #endif // #ifdef MP-WEIXIN
Vue.prototype.StatusBar = e.statusBarHeight;
let custom = wx.getMenuButtonBoundingClientRect();
Vue.prototype.Custom = custom;
Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
// #endif // #ifdef MP-ALIPAY
Vue.prototype.StatusBar = e.statusBarHeight;
Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
// #endif
}
}) },

三、在components文件夹下新建文件:cu-custom.vue

<template>
<view>
<view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
<view class="cu-bar fixed" :style="style" :class="[bgImage!=''?'none-bg text-white bg-img':'',bgColor]">
<view class="action" @tap="BackPage" v-if="isBack">
<text class="cuIcon-back"></text>
<slot name="backText"></slot>
</view>
<view class="content">
<slot name="content"></slot>
</view>
<slot name="right"></slot>
</view>
<image :src="bgImage" class="postyle" :style="[{height:CustomBar + 'px'}]"></image>
</view>
</view>
</template> <script>
export default {
data() {
return {
StatusBar: this.StatusBar,
CustomBar: this.CustomBar
};
},
name: 'cu-custom',
computed: {
style() {
var StatusBar= this.StatusBar;
var CustomBar= this.CustomBar;
var style = `height:${CustomBar}px;padding-top:${StatusBar}px;`;
return style
}
},
props: {
bgColor: {
type: String,
default: ''
},
isBack: {
type: [Boolean, String],
default: false
},
bgImage: {
type: String,
default: ''
},
},
methods: {
BackPage() {
uni.navigateBack({
delta: 1
});
}
}
}
</script> <style>
.postyle{
position: fixed;
width: 100%;
top: 0rpx;
left: 0rpx;
z-index: 2;
} </style>

四、将新建的组件在main.js中注册一下,需要的页面就可以直接引用啦

五、在需要的页面引用

<cu-custom bgColor="green-org" class="colorWhite" :isBack="false">
<block slot="backText"></block>
<block class="info-ifo" slot="content">首页</block>
</cu-custom>

好啦来看看效果吧

uniapp 微信小程序自己封装头部标题栏的相关教程结束。

《uniapp 微信小程序自己封装头部标题栏.doc》

下载本文的Word格式文档,以方便收藏与打印。