uniapp自定义头部(官方状态栏高度var(--status-bar-height)失效后的处理)

时间:2024-11-24 07:00:49

说明:之前都是用uview UI自定义头部,发现现在他的插槽无法解决我的需求后,决定自己写一个,但是遇到了一堆坑,最恶心的是var(–status-bar-height),获取手机状态栏高度这个属性失效了,没办法自己获取手机状态栏高度去了

代码说明:核心函数是状态栏高度(statusBarHeight)+ 底部高度(48px)
这里安卓是44px,ios是48px,我偷懒没做处理,直接用的48px

效果图
效果图

组件代码

<template>
	<view class="myHeader">
		<view class="header">
			<view class="headerBox"
				:style="{ 'padding-top': statusBarHeight +  'px;', 'height': 'calc( '+ statusBarHeight +  'px + 48px);', 'background-color': background}">
				<slot name="header">
				</slot>
			</view>
			<view class="headerBottom" :style="{ 'padding-bottom': 'calc(' + statusBarHeight +  'px + 48px);' }"></view>
		</view>
	</view>
</template>

<script>
	/**
	 * myHeader 固定在头部的内容
	 * 使用方法:
	   	<myHeader>
			<view slot="header">
				内容
			</view>
		</myHeader>
	 */
	export default {
		name: "myHeader",
		props: {
			background: {
				type: String,
				default: "#FFFFFF",
			}
		},
		computed: {},
		data() {
			return {
				statusBarHeight: 44
			};
		},
		created() {
			this.statusBarHeight = this.$store.state.statusBarHeight || 44
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		.headerBox {
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 99;
			// padding-top: var(--status-bar-height);
			// height: calc(var(--status-bar-height) + 48px);
			background-color: #FFFFFF;
		}

		.headerBottom {
			// padding-bottom: calc(var(--status-bar-height) + 48px);
		}
	}
</style>

使用代码

		<myHeader>
			<view slot="header" class="header">
				<view class="headerBoxs">
					<view class="left">
						<text @click="getBack" class="iconfont icon-headeLeft"></text>
					</view>
					<view class="content">
						<view class="tabs">
							<text :class="{active: active == 0}" @click="active = 0">订单</text>
							<text :class="{active: active == 1}" @click="active = 1">售后</text>
						</view>
					</view>
					<view class="right">
					</view>
				</view>
			</view>
		</myHeader>

		<view class="nav" :style="{'top': 'calc(' + statusBarHeight + 'px + 48px)'}">
			<view class="navItem" v-if="active == 0">
				<view class="item" v-for="(item, index) in navList0" :key="index" :class="{active: navIndex0 == index}"
					@click="navIndex0 = index">
					<text>{{item}}</text>
				</view>
			</view>
			<view class="navItem" v-if="active == 1">
				<view class="item" v-for="(item, index) in navList1" :key="index" :class="{active: navIndex1 == index}"
					@click="navIndex1 = index">
					<text>{{item}}</text>
				</view>
			</view>
		</view>



		statusBarHeight: 44,
		
		onLoad(option) {
			this.statusBarHeight = this.$store.state.statusBarHeight || 44
		},