uniapp | 小程序自定义头部组件

前言:在开发小程序的过程中,很经常会遇到各种各样的需求,有些顶部没法很单一的只显示标题和纯色的背景,因此就需要按照项目需求自定义。

思路:先根据设计稿在页面中绘制出结构和样式的内容,接着固定的样式值改成动态的,最后一步把写好的内容搬到组件上去。这里需要的动态值有状态栏的高度和胶囊位置的文本栏高度,都可以通过api获取到。

1.在app.vue页面中统一获取到动态值

globalData: {  
	statusBarHeight: '',  //状态栏高度
	navHeight:'',  //文本内容高度
},
onLaunch: function() {
	let that = this;
	let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	uni.getSystemInfo({
		success(res) {
			let statusBarHeight = res.statusBarHeight;
			let navHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) *2;
			//胶囊在页面中的位置-状态栏高度得到的间距*2 再加上胶囊的高度
			that.globalData.statusBarHeight = statusBarHeight;
			that.globalData.navHeight = navHeight;
		}
	})
},

附胶囊按钮api:getMenuButtonBoundingClientRect() | uni-app官网

系统信息api:getMenuButtonBoundingClientRect() | uni-app官网

 

2.创建一个组件页面把结构放上去就行:

(如果需要判断页面是否有返回箭头的话就从页面中传入barData对象来判断,目前我这个项目暂不需要所以写的比较简单)

<template>
	<view class="custombar" :style="{height:(statusBarHeight+navHeight)+'px'}">
		<view class="status_bar" :style="{height:statusBarHeight+'px'}"></view>
		<view class="nav_bar" :style="{height:navHeight+'px'}">
			<image v-if="barData.hasReturn" class="return" src="/static/image/return.png"></image>
			<view class="title">
				<image src="/static/logo.png"></image>
				<text>uniapp</text>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	export default {
		props:['barData'],
		data() {
			return {
				statusBarHeight:app.globalData.statusBarHeight,
				navHeight:app.globalData.navHeight,
			}
		},
	}
</script>

<style scoped lang="less">
	.custombar{position: fixed;top: 0rpx;left: 0;width: 100%;z-index: 999;text-align: center;height: 45px;background-color: #002FA7;
		.nav_bar{position: relative;z-index: 999;
			.return{position: absolute;transform: translateY(-50%);width: 40rpx;height: 40rpx;top: 50%;left: 30rpx;z-index: 99;}
			.title{position: relative;transform: translate(-50%, -50%);left: 50%;top: 50%;font-size: 0;
				image,text{display: inline-block;vertical-align: middle;}
				image{width: 72rpx;height: 72rpx;margin-right: 14rpx;}
				text{font-size: 34rpx;color: #fff;font-weight: bold;letter-spacing: 6rpx;}
			}
		}
	}
</style>

3.页面效果展示如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值