现成组件:Uniapp去除微信小程序头部导航栏;组件经多次调优,近乎完美;Uniapp实现小程序透明导航栏
之前写过一篇文章:微信小程序顶部去除默认样式后依旧显示返回按钮和顶部页面名称
这篇文章是在微信小程序原生开发的基础上设计的,但是最近又做到了Uni-app的项目,好巧不巧又得适配小程序端,顶部这个导航栏就有得折腾了。好在之前在原生上折腾过一次,这篇文章就整理一下Uni-app上如何去除这个默认样式后,依旧显示标题和返回按钮。
先上效果图:
快速上手:
1. 在App.vue中写入以下代码:
⭕️ 注意:这里我是利用Store去存放“状态栏高度”这个变量,如果你不想用Store,想直接用全局变量也是可以的。但以下我介绍的是利用Store的办法:
<script>
import store from './store'
export default {
onLaunch: function() {
this.GetStatusBarHeight()
},
methods: {
GetStatusBarHeight() {
let that = this;
wx.getSystemInfo({
success: function(res) {
store.commit('setStatusBarHeight',res.statusBarHeight)
},
});
},
}
}
</script>
2. 编写Store文件:
没记错的话Uniapp自带Store,不需要安装,只需要创建store文件夹,并编写index.js 文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);//vue的插件机制
//Vuex.Store 构造器选项
const store = new Vuex.Store({
state:{//存放状态
"statusBarHeight":0
},
getters:{
statusBarHeight: state => {
return state.statusBarHeight
},
},
mutations: {
setStatusBarHeight(state,num) {
state.statusBarHeight = num;
}
}
})
export default store
3. 在Compoents文件夹下新建一个headerNav组件:
4. 贴入以下代码:
<template>
<view class="headerNav" :style="'padding-top:'+(height*2+20)+'rpx'">
<image
src="返回按钮图片路径"
class="navBackImg"
@click="navigateBackPage"
:style="'display:'+(show?'':'none')"
></image>
<view class="navTitle" :style="'margin-right:'+(show?'85rpx':'0')">{{ text }}</view>
</view>
</template>
<script>
import store from '../../store'
export default {
props:['text','showNavBackBtn'],
data(){
return {
height: "",
show:true
}
},
mounted() {
this.height = store.getters.statusBarHeight
if(this.showNavBackBtn !== null){
this.show = this.showNavBackBtn
}
},
methods: {
navigateBackPage: function () {
uni.navigateBack()
},
},
};
</script>
<style scoped>
.navBackImg {
width: 45rpx;
height: 45rpx;
margin-left: 40rpx;
}
.headerNav {
display: flex;
align-items: center;
}
.navTitle {
font-family: 'Arial';
font-style: normal;
font-weight: 700;
font-size: 30rpx;
line-height: 34rpx;
color: #000000;
width: 100%;
display: flex;
justify-content: center;
}
</style>
组件参数 | 意义 | 默认值 | 类型 |
---|---|---|---|
text | 顶部标题 | 无默认值 | string |
showNavBackBtn | 是否显示返回按钮 | true | boolean |
至此,组件的准备工作就结束啦
组件的使用:
1. 在页面中引入该组件:
import headerNav from 'components/headerNav/headerNav'
2. 在文档最顶部使用该组件:
<headerNav text="页面标题" :showNavBackBtn="false"/>