⭐小程序實現自定義底部導航欄
很多時候,微信原生的底部導航欄不能滿足我們的開發需求,因此封裝一個適合自己的底部導航欄組件十分重要。
如何自己封裝? 我們可以利用 navigator 組件 來實現。
效果圖 橫豎雙列
可動態設置:
導航欄背景、文字大小、文字選中顏色、文字本身顏色、導航欄動態渲染、圖標和文字豎排和橫排切換
組件屬性
/**
* 組件的屬性列表
*/
properties: {
// 導航欄背景顏色
backgrounds: {
backgrounds: String,//類型
value: '#fbfbfb'//默認值
},
// 文字原生顏色
color: {
color: String,
value: 'black'
},
// 文字選中樣式
selectedColor: {
selectedColor: String,
value: '#22a6b3'
},
// 文字大小默認為28rpx 單位為rpx
fontSize: {
fontSize: String,
value: '28'
},
// 選中的下標
selected: {
selected: Number,
value: 0
},
// 默認0 圖標和文字並行 1 文字在圖標下面
type: {
selected: Number,
value: 0
},
// 若想要動態設置底部導航欄,則將下面代碼解除注釋
// navList: {
// navList: Array,
// value: [] , // 初始化底部導航欄
// }
},
默認初始值
navList
是對底部導航欄的初始化
/**
* 組件的初始數據
*/
data: {
navList: [{
"pagePath": "/pages/main/index",
"text": "拼車",
"iconPath": "/icons/car.png",
"selectedIconPath": "/icons/car_click.png"
},
{
"pagePath": "/pages/search/index",
"text": "搜索",
"iconPath": "/icons/search.png",
"selectedIconPath": "/icons/search_click.png"
},
{
"pagePath": "/pages/order/index",
"text": "訂單",
"iconPath": "/icons/order.png",
"selectedIconPath": "/icons/order_click.png"
},
{
"pagePath": "/pages/my/index",
"text": "個人中心",
"iconPath": "/icons/my.png",
"selectedIconPath": "/icons/my-click.png"
}
],
},
與此對應的是:app.json里面 需要 將 tabBar 的 custom屬性設置為 true
"tabBar": {
"custom": true,
"color": "#999",
"selectedColor": "#22a6b3",
"backgroundColor": "#f3fbfb",
"position": "bottom",
"borderStyle": "black",
"list": [{
"pagePath": "pages/main/index",
"text": "拼車",
"iconPath": "./icons/car.png",
"selectedIconPath": "./icons/car_click.png"
},
{
"pagePath": "pages/search/index",
"text": "搜索",
"iconPath": "./icons/search.png",
"selectedIconPath": "./icons/search_click.png"
},
{
"pagePath": "pages/order/index",
"text": "訂單",
"iconPath": "./icons/order.png",
"selectedIconPath": "./icons/order_click.png"
},
{
"pagePath": "pages/my/index",
"text": "個人中心",
"iconPath": "./icons/my.png",
"selectedIconPath": "./icons/my-click.png"
}
]
},
編寫 組件 wxml
<!--components/menuBtn/menuBtn.wxml-->
<view class="tabs enHigh" style=" background: {{ backgrounds }}; color: {{color}}; " >
<view class="meunBtn" style="font-size: {{fontSize}}rpx;" wx:for="{{navList}}" wx:key="index">
<navigator url="{{item.pagePath}}" class="nav {{type == 1 ? 'column' : ''}}" open-type="switchTab" hover-class="none">
<view class="left">
<image src="{{selected == index ? item.selectedIconPath : item.iconPath}}"></image>
</view>
<view style="color: {{selected == index ? selectedColor : color}};{{ type == 1 ? 'margin-top:2rpx' : 'margin-left: 4rpx;'}}">{{item.text}}</view>
</navigator>
</view>
</view>
使用組件
在xxx.json中
{
"usingComponents": {
"menuBtn": "/components/menuBtn/menuBtn"
}
}
xxx.wxml
<menuBtn selected="0"></menuBtn>
源碼下載
demo演示: 該倉庫將不定期更新其他組件~