線上服務咨詢
Article/文章
記錄成長點滴 分享您我感悟
mpvue中小程序自定義導航組件開發(fā)的介紹(代碼示例)
這篇筆記主要記錄一下基于mpvue的小程序中實現自定義導航的思路及應用。分享出來拋磚引玉,如有謬誤或優(yōu)化空間,歡迎交流。
小程序的配置項navigationStyle設置為custom之后,導航欄只保留右上角膠囊按鈕,顏色、標題文字內容均可以自定義,可以此實現導航欄的個性化需求,實際應用如沉浸式視頻播放頁等。
小程序7.0.0之后的版本開始支持自定義單個頁面的導航欄,將頁面的navigationStyle
設置為custom
即可。mpvue的配置方式如下:
由于不同操作系統(tǒng)、不同機型的導航欄高度是不同的,所以自定義導航欄核心要解決的問題是不同機型中導航欄高度的兼容問題。
如上圖所示,導航欄一共由兩部分組成:狀態(tài)欄和標題欄。狀態(tài)欄就是用來展示時間、網絡狀態(tài)的那一欄,全面屏(劉海屏幕)的機型中狀態(tài)欄會比其他屏幕高很多:ios系統(tǒng)帶劉海屏的都是44,其他都為20,包括pad。 而安卓機的數值則更多。我們可以通過微信的apiwx.getSystemInfo獲取狀態(tài)欄的高度(statusBarHeight)。而標題欄高度不能通過小程序api獲取到,通過同級多個機型的測試數據,我們基本可以按照ios中44px安卓中48px來算。
這樣一來就好辦了,通過statusBarHeight獲取到狀態(tài)欄高度后,再判斷當前的系統(tǒng)加上對應的標題欄后,就可以獲取到正確的導航欄高度了。
template中的html代:(因為小程序中的video組件有著最高的層級,是不會被普通html標簽覆蓋的,所以導航欄組件中全部采用了<cover-view>標簽。):
<template> <p class="comp-navbar"> <!-- 占位欄 --> <cover-view class="placeholder-bar" :style="{height: navBarHeight + 'px'}"> </cover-view> <!-- 導航欄主體 --> <cover-view class="navbar" :style="{height: navBarHeight + 'px',backgroundColor:navBackgroundColor}"> <!-- 狀態(tài)欄 --> <cover-view class="nav-statusbar" :style="{height: statusBarHeight + 'px'}"></cover-view> <!-- 標題欄 --> <cover-view class="nav-titlebar" :style="{height: titleBarHeight + 'px' }"> <!-- home及后退鍵 --> <cover-view class="bar-options"> <cover-view v-if="backVisible" class="opt opt-back" @click="backClick()"> 沈陽微信小程序 <cover-image class="back-image" src="/static/images/back.png"></cover-image> </cover-view> <cover-view class="line" v-if="backVisible && homePath"></cover-view> <cover-view v-if="homePath" class="opt opt-home" @click="homeClick()"> <cover-image class="home-image" src="/static/images/home.png"></cover-image> </cover-view> </cover-view> <!-- 標題 --> <cover-view class="bar-title" :style="[{color:titleColor}]">{{title}}</cover-view> </cover-view> </cover-view> </p></template>
js代碼:
beforeMount() { const self = this; wx.getSystemInfo({ success(system) { console.log(`system:`, system); self.statusBarHeight = system.statusBarHeight; self.platform = system.platform; let platformReg = /ios/i; if (platformReg.test(system.platform)) { self.titleBarHeight = 44; } else { self.titleBarHeight = 48; } self.navBarHeight = self.statusBarHeight + self.titleBarHeight; } }); },小程序,mpvue