Skip to content

自定义导航栏

微信小程序 navigationStyle: "custom" 下需自行处理状态栏高度和胶囊避让。项目封装了 useNavbar composable 和 custom-navbar 组件,页面直接用组件即可,一般不需要手动调 composable。

custom-navbar 组件

vue
<custom-navbar title="页面标题" fixed placeholder />

Props

参数说明类型默认值
title标题文字string""
titleColor标题颜色stringvar(--color-text)
bgColor背景色stringvar(--color-bg)
iconColor图标颜色stringvar(--color-text)
showBack显示返回按钮booleantrue
showHome显示首页按钮booleanfalse
backIcon返回按钮图标名string"arrow-left"
backIconSize返回按钮图标大小string"40rpx"
fixed固定到顶部booleantrue
placeholderfixed 时自动撑出等高占位booleanfalse
navBarHeight导航栏内容高度,仅 H5/App 生效(小程序走胶囊计算)number44

Events

事件说明
back点击返回按钮
home点击首页按钮

Slots

插槽说明
left返回/首页按钮之后
center标题之后,用 #center 可替换标题
right右侧区域

useNavbar composable

需要手动控制布局(如沉浸式、scroll-view 独立滚动)时使用:

ts
import { useNavbar } from "@/composables/useNavbar"

const { totalHeight, contentPaddingTop } = useNavbar()

// TabBar 页面
const navbar = useNavbar({ hasTabbar: true })

返回值

属性类型说明
statusBarHeightRef<number>状态栏高度
navBarHeightnumber导航栏内容高度(H5/App 为 44,小程序为胶囊计算值)
totalHeightComputedRef<number>导航栏总高度(状态栏 + 内容高度)
contentPaddingTopComputedRef<string>totalHeight + "px",直接用作 paddingTop
safeAreaBottomRef<number>安全区域底部高度
menuButtonRef<MenuButtonRect | null>胶囊按钮位置信息
menuButtonWidthComputedRef<number>胶囊按钮宽度
menuButtonLeftComputedRef<number>胶囊按钮左侧距屏幕左边距离
menuButtonRightGapComputedRef<number>胶囊按钮右侧距屏幕右边距离
contentWidthComputedRef<number>内容区域可用宽度(避开胶囊)
platformRef<string>平台标识
windowWidthRef<number>窗口宽度
init() => void重新初始化(setup 阶段已自动调用)

场景示例

标准用法

导航栏固定,内容从下方开始:

vue
<custom-navbar title="用户管理" fixed placeholder />

沉浸式

轮播图铺到顶部,导航栏透明叠加,内容区手动 paddingTop

vue
<template>
  <view class="hero" :style="{ paddingTop: navbar.totalHeight.value + 'px' }">
    <custom-navbar
      fixed :placeholder="false"
      bg-color="transparent"
      title-color="var(--color-text-inverse)"
      icon-color="var(--color-text-inverse)"
      :show-back="false"
    />
    <wd-swiper :list="swiperList" autoplay />
  </view>
</template>

<script setup>
import { useNavbar } from "@/composables/useNavbar"
const navbar = useNavbar({ hasTabbar: true })
</script>

常见坑点

坑点解决
内容与导航栏重叠placeholder,或 paddingTop: totalHeight
按钮与胶囊重叠menuButtonRightGap 避让,或直接用 custom-navbar(已内置)
getMenuButtonBoundingClientRect 返回 0iOS 预览偶发,useNavbar 内置 6 次重试 + 默认值兜底
页面出现多余滚动不要无脑 min-height: 100vh,让内容自然撑开
状态栏高度不准不要用 CSS 变量 --status-bar-height(小程序端固定 25px),用 useNavbar 动态获取

参考资源

基于 MIT 许可发布 · 如需部署协助或二开定制,请查看 支持与合作