Custom Navbar 组件使用说明
功能特性
- 自动监听页面滚动
- 滚动时导航栏变为纯色背景
- 回到顶部时导航栏变为透明
- 支持自定义背景色和滚动阈值
- 提供滚动状态事件回调
基本用法
<template>
<view>
<custom-navbar title="页面标题" />
<!-- 页面内容 -->
</view>
</template>
高级用法
<template>
<view>
<custom-navbar
title="古刹巡礼"
:backgroundColor="'#FAF8F3'"
:scrollThreshold="100"
:enableScrollEffect="true"
@scroll-change="onScrollChange"
@scroll="onScroll"
>
<template #right>
<view class="right-button">更多</view>
</template>
</custom-navbar>
<!-- 页面内容 -->
</view>
</template>
<script>
export default {
methods: {
onScrollChange(data) {
console.log('滚动状态变化:', data.isScrolled);
},
onScroll(data) {
console.log('滚动位置:', data.scrollTop);
}
}
}
</script>
Props 参数
| 参数 |
类型 |
默认值 |
说明 |
| title |
String |
'' |
导航栏标题 |
| backIcon |
String |
CommonEnum.BACK_BUTTON |
返回按钮图标 |
| showBack |
Boolean |
true |
是否显示返回按钮 |
| backgroundColor |
String |
'#ffffff' |
滚动时的背景色 |
| scrollThreshold |
Number |
50 |
滚动阈值(像素) |
| enableScrollEffect |
Boolean |
true |
是否启用滚动效果 |
Events 事件
| 事件名 |
参数 |
说明 |
| back |
- |
点击返回按钮时触发 |
| scroll-change |
{ isScrolled, scrollTop } |
滚动状态变化时触发 |
| scroll |
{ scrollTop, isScrolled } |
页面滚动时触发 |
方法
| 方法名 |
参数 |
说明 |
| setScrollState |
scrollTop |
手动设置滚动状态 |
样式定制
组件会自动添加以下 CSS 类:
.navbar-scrolled: 滚动状态下的样式
- 过渡动画:背景色变化有 0.3s 的过渡效果
- 阴影效果:滚动时自动添加阴影
注意事项
- 重要:需要在父页面的
onPageScroll 生命周期中调用组件的 handlePageScroll 方法
- 滚动效果默认启用,可通过
enableScrollEffect 关闭
- 背景色变化有平滑过渡动画
- 组件使用
ref 引用,确保在页面中正确引用
完整使用示例
方法一:使用 Mixin(推荐)
<template>
<view>
<custom-navbar
ref="customNavbar"
title="页面标题"
backgroundColor="#FAF8F3"
:scrollThreshold="50"
@scroll-change="onScrollChange"
/>
<!-- 页面内容 -->
</view>
</template>
<script>
import CustomNavbar from "@/components/custom-navbar/custom-navbar.vue";
import PageScrollMixin from "@/mixins/page-scroll-mixin.js";
export default {
mixins: [PageScrollMixin], // 自动处理滚动事件
components: {
CustomNavbar
},
methods: {
onScrollChange(data) {
console.log('滚动状态变化:', data.isScrolled);
}
}
}
</script>
方法二:手动处理
<template>
<view>
<custom-navbar
ref="customNavbar"
title="页面标题"
backgroundColor="#FAF8F3"
:scrollThreshold="50"
@scroll-change="onScrollChange"
/>
<!-- 页面内容 -->
</view>
</template>
<script>
import CustomNavbar from "@/components/custom-navbar/custom-navbar.vue";
export default {
components: {
CustomNavbar
},
// 页面生命周期 - 必须添加
onPageScroll(e) {
// 将页面滚动事件传递给导航栏组件
if (this.$refs.customNavbar) {
this.$refs.customNavbar.handlePageScroll(e);
}
},
methods: {
onScrollChange(data) {
console.log('滚动状态变化:', data.isScrolled);
}
}
}
</script>