UniApp跨平台开发实战:深度封装高性能自定义导航栏组件
一、导航栏架构设计
多端兼容的自定义导航栏解决方案:
// 核心组件结构
export default {
props: {
title: String,
backgroundColor: {
type: String,
default: '#ffffff'
},
showBack: {
type: Boolean,
default: true
}
},
data() {
return {
statusBarHeight: 0,
navBarHeight: 44,
isAndroid: false
}
},
created() {
const sysInfo = uni.getSystemInfoSync()
this.statusBarHeight = sysInfo.statusBarHeight
this.isAndroid = sysInfo.platform === 'android'
// 安卓平台导航栏高度调整
if (this.isAndroid) {
this.navBarHeight = 48
}
},
methods: {
handleBack() {
uni.navigateBack()
}
}
}
核心优势:多端适配、原生体验、性能优化、高度可定制
二、高级功能实现
1. 沉浸式状态栏
// 页面生命周期处理
onReady() {
this.setNavBarStyle()
},
methods: {
setNavBarStyle() {
// 设置状态栏样式
uni.setNavigationBarColor({
frontColor: this.textColor,
backgroundColor: this.backgroundColor,
animation: {
duration: 300,
timingFunc: 'easeInOut'
}
})
// 动态调整胶囊位置
#ifdef MP-WEIXIN
const menuInfo = wx.getMenuButtonBoundingClientRect()
this.capsulePosition = {
top: menuInfo.top,
right: menuInfo.right
}
#endif
},
// 渐变效果处理
handleScroll(e) {
const scrollTop = e.scrollTop
const opacity = Math.min(scrollTop / 100, 1)
this.bgOpacity = opacity
this.textColor = opacity > 0.5 ? '#000000' : '#ffffff'
this.setNavBarStyle()
}
}
2. 动态搜索框集成
// 搜索框组件逻辑
data() {
return {
isFocus: false,
searchValue: '',
showCancel: false
}
},
methods: {
handleFocus() {
this.isFocus = true
this.showCancel = true
this.$emit('focus')
},
handleBlur() {
if (!this.searchValue) {
this.isFocus = false
this.showCancel = false
}
this.$emit('blur')
},
handleCancel() {
this.searchValue = ''
this.isFocus = false
this.showCancel = false
uni.hideKeyboard()
this.$emit('cancel')
}
}
// 动画效果样式
.search-box {
transition: all 0.3s ease;
&.active {
width: 75%;
}
}
三、多端适配方案
1. 小程序原生组件封装
// 条件编译处理多端差异
// #ifdef MP-WEIXIN
const menuInfo = wx.getMenuButtonBoundingClientRect()
this.navBarHeight = menuInfo.bottom + menuInfo.top - this.statusBarHeight
// #endif
// #ifdef H5
this.navBarHeight = 44
if (document.documentElement.clientWidth > 500) {
this.navBarHeight = 60
}
// #endif
// #ifdef APP-PLUS
this.navBarHeight = 44
if (plus.os.name === 'Android') {
this.navBarHeight = 48
}
// #endif
// 动态样式计算
computed: {
navBarStyle() {
return {
height: `${this.statusBarHeight + this.navBarHeight}px`,
paddingTop: `${this.statusBarHeight}px`,
backgroundColor: this.backgroundColor
}
},
titleStyle() {
return {
color: this.textColor,
lineHeight: `${this.navBarHeight}px`
}
}
}
四、性能优化实践
- 渲染优化:使用CSS替代JS动画
- 事件节流:滚动事件添加节流处理
- 内存管理:及时销毁事件监听
- 图片压缩:导航图标使用SVG格式
- 条件编译:按平台加载不同资源