前言: 在开发小程序过程中,如果你需要根据不同用户角色显示不同底部导航;或者导航样式需要个性化设计。此时就需要用到自定义底部导航 custom-tab-bar。
具体操作:
1、根目录下创建custom-tab-bar目录
2、在app.json文件中配置导航信息
"tabBar": {
"custom": true, // 开启自定义导航
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [ // 配置导航按钮信息 如果按条件显示不同按钮的话;这里一定要把所有的按钮全量的都配置上(比如当前示例中,登录前显示首页和我的两个按钮;登录后显示首页、工作台、我的三个按钮;在这里要把可能出现的按钮全部配置上)
{
"pagePath": "pages/home/index", //页面路由
"iconPath": "/img/icon_home_def.png", // 按钮图标
"selectedIconPath": "/img/icon_navbar_homesel.png", // 选中时图标
"text": "首页" // 按钮文字
},
{
"pagePath": "pages/workbench/index",
"iconPath": "/img/icon_navbar_workdef.png",
"selectedIconPath": "/img/icon_navbar_worksel.png",
"text": "工作台"
},
{
"pagePath": "pages/my/index",
"iconPath": "/img/icon_navbar_userdef.png",
"selectedIconPath": "/img/icon_navbar_usersel.png",
"text": "我的"
}
]
},
3、custom-tab-bar/index.wxml 文件内容
<!--miniprogram/custom-tab-bar/index.wxml-->
<cover-view class="tab-bar">
<cover-view class="tab-bar-border"></cover-view>
<cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
<cover-image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
<cover-view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</cover-view>
</cover-view>
</cover-view>
4、custom-tab-bar/index.js 文件内容
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#ff0000",
list: []
},
attached() {
this.setData({
list: [
{
"pagePath": "/pages/home/index",
"iconPath": "/img/icon_home_def.png",
"selectedIconPath": "/img/icon_navbar_homesel.png",
"text": "首页"
},
{
"pagePath": "/pages/my/index",
"iconPath": "/img/icon_navbar_userdef.png",
"selectedIconPath": "/img/icon_navbar_usersel.png",
"text": "我的"
}
]
})
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
5、custom-tab-bar/index. wxss文件内容
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 48px;
padding-top: 4px;
background: white;
display: flex;
padding-bottom: env(safe-area-inset-bottom);
}
.tab-bar-border {
background-color: rgba(0, 0, 0, 0.33);
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 1px;
transform: scaleY(0.5);
}
.tab-bar-item {
flex: 1;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.tab-bar-item cover-image {
width: 27px;
height: 27px;
}
.tab-bar-item cover-view {
font-size: 10px;
}
6、导航跳转到的页面内
// 这样按钮才能正确显示选中效果
onShow(){
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
},
7.效果:
登录前:
文章来源:https://www.toymoban.com/news/detail-512488.html
登录后:文章来源地址https://www.toymoban.com/news/detail-512488.html
到了这里,关于小程序自定义底部导航 custom-tab-bar的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!