uniapp自定义导航栏,采用粘性定位

发布于:2025-06-12 ⋅ 阅读:(118) ⋅ 点赞:(0)

1.使用自定义状态栏,在pages.json中设置

{
			"path": "pages/index/index",
			"style": {
				"navigationStyle": "custom" //自定义导航栏
			}
		},

2.在app.vue中获取胶囊信息

<script setup lang="ts">
	import { useSystemStore } from "@/store/index";
	
	const systemStore = useSystemStore();
	import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
	onLaunch(() => {
		let obj = uni.getMenuButtonBoundingClientRect()
		
		let { top, bottom, height } = obj
		systemStore.setMenuButtonBounding({ top, bottom, height })
	});
	onShow(() => {
		console.log("App Show");
	});
	onHide(() => {
		console.log("App Hide");
	});
</script>
<style lang="scss">
	/*每个页面公共css */
	page, .page-content{
		width: 100%;
		height: 100%;
	}
	@import "uview-plus/index.scss";
</style>

3.封装defaultNavbar.vue组件

<template>
	<view class="page-content">
		<view class="pageTitle" :style="{ 'height': `${menuButtonBounding.bottom + 5}px`, 'position': 'relative' }">
			<view class="titleText"
				:style="{ 'height': `${menuButtonBounding.height}px`, 'line-height': `${menuButtonBounding.height}px`, 'bottom': '5px', 'position': 'absolute', 'text-align': 'center' }">
				<view class="backIcon" @click="linkToBack">
					<i class="iconfont icon-fanhui zlcIcon"></i>
				</view>
				<view class="text">
					{{ props.pageTitle }}
				</view>
				<view class="menuButton">
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { defineProps } from "vue"
	import { useSystemStore } from "@/store/index";
	const systemStore = useSystemStore();
	//胶囊信息
	let { menuButtonBounding } = systemStore
	interface Props {
		pageTitle : string
	}
	//传递的页面标题
	const props = withDefaults(defineProps<Props>(), {
		pageTitle: '页面标题'
	})

	//返回上一页
	let linkToBack = () : void => {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	@import url('@/iconfont/iconfont.css');

	.page-content {
		position: -webkit-sticky; /* Safari需要前缀 */
		position: sticky;
		z-index: 99;
		width: 100vw;
		height: fit-content;
		top: 0;
		background: linear-gradient(to bottom right, rgba(255, 252, 253, 1), rgba(255, 231, 237, 1), rgba(254, 252, 252, 1));


		.pageTitle {

			border-bottom: 1px solid #f8f2ff;


			.titleText {
				width: 100%;
				white-space: nowrap;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				padding: 0 20rpx;
				box-sizing: border-box;
				text-align: center;
				font-weight: bold;

				.backIcon {
					font-size: 30rpx;
					width: 40rpx;
					text-align: center;
					color: rgba(36, 37, 83, 1);

				}

				.text {
					color: rgba(36, 38, 81, 1);

				}

				.menuButton {
					width: 40rpx;
				}
			}
		}
	}
</style>

4.在页面中使用

 5.效果图