uniapp 微信小程序自定义导航栏

uniapp 微信小程序自定义导航栏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<template>
<view class="container-nav" :style="{'height': custom_height + 'px', 'line-height': custom_height + 'px', 'padding-top': menu_button.top + 'px'}">
<view v-if="has_btn" class="btns"
:style="{'padding-left': get_btns_padding_left + 'px', 'width': menu_button.width + 'px'}">
<view v-if="has_show_back" class="btn" @click="handleToBack">
<image src="https://i.loli.net/2021/01/22/c7wkx89sZQdz1BV.png"></image>
</view>
<view v-else class="btn" @click="handleToHome">
<image src="https://i.loli.net/2021/01/22/PjIkZVqaLN28SGi.png"></image>
</view>
</view>
<view class="title" :style="{'padding-right': get_title_padding_right + 'px'}">
{{ title }}
</view>
</view>
</template>

<script>
export default {
props: {
title: {
type: String,
default: '标题',
},
// 是否显示跳转按钮
has_btn: {
type: Boolean,
default: true,
},
},
data () {
return {
custom_width: 0,
custom_height: 0,
system: {},
menu_button: {},
}
},
computed: {
// 是否显示返回按钮
has_show_back () {
const page = getCurrentPages();

return page.length > 1;
},
// 获取按钮左间距
get_btns_padding_left () {
return this.system.windowWidth - this.menu_button.right;
},
// 获取标题右间距
get_title_padding_right () {
if (!this.has_show_back && !this.has_btn) return 0;

return this.get_btns_padding_left + this.menu_button.width;
},
},
mounted () {
this.handleInit();
},
methods: {
handleInit () {
const self = this;

uni.getSystemInfo({
success: function (e) {
const rect = uni.getMenuButtonBoundingClientRect();

// 如果高度无法获取而需要静等一会重新调用。(注:这应该是历史问题了,至少这段时间我没有遇到过)
if (!e.statusBarHeight || !rect.bottom) {
return setTimeout(() => {
self.handleInit();
}, 50);
}

self.system = e;
self.menu_button = rect;
self.custom_height = rect.bottom - e.statusBarHeight;
},
});
},
handleToHome () {
return uni.reLaunch({
url: '/pages/index/index',
});
},
handleToBack () {
return uni.navigateBack();
},
},
}
</script>

<style lang="scss" scoped>
.container-nav {
display: flex;
background-color: #FFFFFF;
}

.title {
flex: 1;
text-align: center;
}

.btns {
display: flex;

>.btn {
display: flex;
align-items: center;

>image {
width: 22px;
height: 22px;
}
}
}
</style>

效果

往上