问题:用uniapp写小程序的时候,原生导航栏满足不了需求,uniapp官网推荐的占位view方法在不同的手机上显示有问题
解决方法:自定义导航栏
步骤:
- 封装导航栏组件(用于复用)
- 通过
uni.getSystemInfoSync()
和uni.getMenuButtonBoundingClientRect()
接口获取导航栏位置信息,动态设置位置 - 将获取到的参数传递给组件
01.封装导航栏组件
在项目根目录下新建components文件夹,在components里新建目录navbar,新建navbar.vue
<template>
<view class="status_bar">
<view class="title">{{title}}</view>
</view>
</template>
<script>
export default {
data() {
return {
//动态参数
title:"",
buttonHeight:0,
statusBarHeight:0,
buttonTop:0
}
},
mounted() {
}
}
</script>
<style lang="scss" scoped>
/*默认样式设置*/
.status_bar{
width: 100%;
position: relative;
.title{
width: 100%;
text-align: center;
position: absolute;
left: 0;
}
}
</style>
02.获取导航栏位置参数
uniapp官网给了uni.getSystemInfoSync()
和uni.getMenuButtonBoundingClientRect()
两个接口用于获取手机顶部状态栏高度和微信中的胶囊按钮位置
uni.getSystemInfoSync()
获取手机顶部状态栏参数uni.getMenuButtonBoundingClientRect()
获取微信中的胶囊按钮参数
将所需参数封装成对象放入vuex中
vuex
03.组件获取vuex中的参数
navbar.vue
<template>
<view class="status_bar" :style="{height:statusBarHeight+'px'}">
<view class="title" :style="{height:buttonHeight+'px',top:buttonTop+'px',lineHeight:buttonHeight+'px'}">{{title}}</view>
</view>
</template>
<script>
export default {
data() {
return {
//动态参数
title:"",
buttonHeight:0,
statusBarHeight:0,
buttonTop:0
}
},
mounted() {
//从vuex里获取参数
this.statusBarHeight=this.$store.state.statusBarHeight
this.buttonHeight=this.$store.state.buttonHeight
this.title=this.$store.state.title;
this.buttonTop=this.$store.state.buttonTop;
}
}
</script>
<style lang="scss" scoped>
/*默认样式设置*/
.status_bar{
width: 100%;
position: relative;
.title{
width: 100%;
text-align: center;
position: absolute;
left: 0;
}
}
</style>
04.预览
微信开发者工具中
手机上