When we develop small programs, the built-in header navigation style often cannot meet the needs, so we can only customize the navigation. Next, we briefly introduce how to achieve it:
1. Remove the built-in head navigation
To customize the header navigation, first go to the pages.json folder, find the corresponding page, and then write the code in the style:
// 找到对应页面,在style中写下所需代码
{
"path": "pages/about/apply",
"style": {
"navigationStyle": "custom" // 注意一定要书写此行代码
}
}
2. Encapsulate custom header navigation
A small program may have multiple pages that use custom header navigation, so for ease of use, the navigation can be packaged as a component. The specific code is as follows:
1. HTML code
<template> <view class="custom-nav"> <view class="my-nav" :style="[{ background }, { color }, { height }, { paddingTop }]" > <!-- 左侧返回按钮 --> <view class="left" @click="onBack" v-if="back" :style="[{ color }, { paddingTop }]" > <u-icon name="arrow-left" :color="color" size="36"></u-icon> </view> <!-- 中间标题文字 --> <view class="title" :style="{color}"> { { title }} </view> </view> <view :style="{height}"></view> </view> </template>
2. css code
<style lang="scss"> .my-nav{ position: fixed; width: 100%; display: flex; align-items: center; justify-content: center; font-size: 26rpx; z-index: 100; padding-bottom: 10rpx; .left { float: left; position: absolute; // width: 100rpx; line-height: 90rpx; top: 0; bottom: 0; left: 20rpx; margin: auto; } .title { padding: 0; font-size: 36rpx; font-family: Source Han Sans CN; // color: #FFFFFF; } } </style>
3. js code
<script> export default { data() { return { height: 0, paddingTop: 0, }; }, // props: ["title", "back"], props: { title: { // 标题文字(默认为空) type: String, default: "", }, color: { // 标题和返回按钮颜色(默认白色) type: String, default: "#fff", }, //建议使用background 因为使用backgroundColor,会导致不识别渐变颜色 background: { // 背景颜色(不传值默认透明) type: String, default: "transparent", }, back: { // 是否显示返回按钮(不传值默认不显示) type: Boolean, default: true, }, }, created() { const demo = uni.getMenuButtonBoundingClientRect(); this.paddingTop = demo.top * 2 + "rpx"; // 状态栏高度 const statusBarHeight = uni.getSystemInfoSync().statusBarHeight; // 导航栏高度(标题栏高度)一般都为44px,所以我这里直接使用44 // 总体高度 = 状态栏高度 + 导航栏高度 this.height = (statusBarHeight + 44) * 2 + 'rpx' }, methods: { // 左侧返回按钮调用 //直接返回上一级 onBack() { // this.$emit("onBack"); uni.navigateBack({ delta: 1 // 返回的页面数 }) }, }, }; </script>
3. Use a custom header navigation component
(1) Import the component first
import topNav from "../components/topNav/topNav.vue";
(2) Registration component
export default {
components: {
topNav,
},
}
(3) Using components
<topNav :background="backgroundColor" title="首页"></topNav>
// backgroundColor这里传的是渐变色,除了传颜色,也可以传背景图
// 以下代码是写在js中的
data() {
return {
backgroundColor: "linear-gradient(to top, #3F77FE, #294EFA)",
}
4. Rendering