前言
在使用uni-app开发app或者是微信小程序时,使用原生的导航栏有时无法满足我们的一些特殊需要,我们可以封装一个导航栏用于复用。
一、创建导航栏组件
二、customNavbar.vue 文件原码
<template>
<view class="customNavbar" :style="{'background':bgColor}">
<view class="system" :style="{'height':`${statusBar * 2}rpx`}"></view>
<view class="navbar" :style="{'height':`${(customBar - statusBar) * 2}rpx`}">
<view class="left">
<slot name="left">
<view @click="back()">返回</view>
<view @click="back()" v-if="isPageUp">返回</view>
<view @click="homePage()" v-else>首页</view>
</slot>
</view>
<view class="content">
<slot name="content">{{ title }}</slot>
</view>
<view class="right">
<slot name="right">
</slot>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
statusBar: 0,
customBar: 0,
platform: "",
isPageUp: true,
}
},
props: {
leftText: {
type: String,
default: ""
},
title: {
type: String,
default: ""
},
rightText: {
type: String,
default: ""
},
bgColor: {
type: String,
default: "#fff"
},
},
mounted() {
uni.getSystemInfo({
success: (res) => {
this.platform = res.platform
this.statusBar = res.statusBarHeight
const custom = wx.getMenuButtonBoundingClientRect()
this.customBar = custom.bottom + custom.top - res.statusBarHeight
this.statusBar = res.statusBarHeight
this.customBar = res.statusBarHeight + 45
if (res.platform == "android") {
this.statusBar += 3
this.customBar += 3
}
}
})
let pages = getCurrentPages()
if (pages[pages.length - 2]) {
this.isPageUp = true
} else {
this.isPageUp = false
}
},
methods: {
back() {
console.log("返回上一页!")
uni.navigateBack()
},
homePage() {
console.log("返回首页!")
uni.switchTab({
url: '/pages/index/index'
})
}
}
}
</script>
<style lang="scss" scoped>
.customNavbar {
.system {
width: 100vw;
background: transparent;
}
.navbar {
width: 100vw;
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
position: relative;
padding: 0 30rpx;
}
.left,
.right {
width: 88rpx;
}
.left {
text-align: left;
}
.content {
text-align: center;
}
.right {
text-align: right;
}
}
</style>
三、组件的使用
<template>
<view class="content">
<customNavbar title="首页"></customNavbar>
</view>
</template>
<script>
import customNavbar from '@/components/customNavbar/customNavbar.vue'
export default {
components: {
customNavbar
},
data() {
return {
}
},
mounted() {
},
methods: {
}
}
</script>
<style lang="scss" scoped></style>
四、全局组件的注册
在pages.json文件中添加以下代码
"easycom": {
"autoscan": true
},
五、效果图展示
封装的不是很完善,后期会慢慢优化。