上一篇:uniapp自定义导航栏/导航栏与小程序胶囊保持平行
需求:多个页面都需要自定义导航栏,多个界面使用相同代码逻辑,故针对相同的代码逻辑进行抽取
步骤:
1.将状态栏的高度、导航栏的高度封装到mixins中
navbar.js
export const navbar = {
data() {
return {
statusBarHeight: 20,
navBarHeight: 40,
}
},
methods: {
getSystemInfo() {
// #ifdef MP-WEIXIN
this.statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'];
// 获取微信胶囊的位置信息 width,height,top,right,left,bottom
const custom = wx.getMenuButtonBoundingClientRect()
// console.log(custom)
// 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
this.navBarHeight = custom.height + (custom.top - this.statusBarHeight) * 2
// console.log("导航栏高度:" + this.navBarHeight)
// #endif
},
}
}
2.将状态栏和导航栏封装到一个组件中
navBar.vue
<template>
<view class="navBarBox" :style="{background:backgroundColor }">
<!-- 状态栏占位 -->
<view class="statusBar" :style="{ height:statusBarHeight+'px' }"></view>
<!-- 真正的导航栏内容 -->
<view class="navBar" :style="{ height:navBarHeight+'px',color:textColor }">
<view>{{title}}</view>
</view>
</view>
</template>
<script>
import {
navbar
} from '../mixins/navbar.js'
export default {
name: "navBar",
mixins: [navbar],
data() {
return {
};
},
props: {
title: {
type: String,
default: ""
},
textColor: {
type: String,
default: "#FFF"
},
backgroundColor: {
type: String,
default: ""
}
},
methods: {
goBack() {
uni.navigateBack({
delta: 1
})
}
},
created() {
this.getSystemInfo();
}
}
</script>
<style>
.navBar {
width: 750rpx;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
font-size: 34rpx;
font-weight: 500;
color: rgba(255, 255, 255, 1);
}
</style>
3.使用组件
<template>
<view class="detail">
<navBar title="详情" textColor="black" backgroundColor="#FFF"/>
</view>
</template>
<script>
import navBar from '../../components/navBar.vue';
export default {
components:{
navBar
},
}
</script>
<style lang="scss">
.detail{
height: 100vh;
background: rgba(245, 247, 249, 1);
}
</style>