开始前,请先完成底部导航的开发,详见
【微信小程序-原生开发】实用教程02-添加全局页面配置、页面、底部导航
https://sunshinehu.blog.csdn.net/article/details/128705866
显然,纯文字的底部导航有点low,还是需要有图标的才酷,下面我们一起来实现
1. 修改 tabBar 配置
在 app.json 的 tabBar 配置中新增
"custom": true,
即启用用户自定义的 tabar,但之前的 list 配置留着,别删 !!!
2. 添加自定义的 tabBar 代码
在项目目录下新建文件夹 custom-tab-bar
(必须是这个名字!)
文件夹中依次创建以下文件
custom-tab-bar\data.js
export default [ { icon: 'home', text: '首页', url: 'pages/index/index', }, { icon: 'usergroup', text: '家庭成员', url: 'pages/member/index', }, { icon: 'tips', text: '圆梦宝典', url: 'pages/bible/index', }, { icon: 'user', text: '我的世界', url: 'pages/me/index', }, ];
custom-tab-bar\index.js
import TabMenu from './data'; Component({ data: { active: 0, list: TabMenu, }, methods: { onChange(event) { this.setData({ active: event.detail.value }); wx.switchTab({ url: this.data.list[event.detail.value].url.startsWith('/') ? this.data.list[event.detail.value].url : `/${this.data.list[event.detail.value].url}`, }); }, init() { const page = getCurrentPages().pop(); const route = page ? page.route.split('?')[0] : ''; const active = this.data.list.findIndex( (item) => (item.url.startsWith('/') ? item.url.substr(1) : item.url) === `${route}`, ); this.setData({ active }); }, }, });
custom-tab-bar\index.json
{ "component": true, "usingComponents": { "t-tab-bar": "tdesign-miniprogram/tab-bar/tab-bar", "t-tab-bar-item": "tdesign-miniprogram/tab-bar/tab-bar-item", "t-icon": "tdesign-miniprogram/icon/icon" } }
custom-tab-bar\index.wxml
<t-tab-bar value="{{active}}" bindchange="onChange" split="{{false}}" > <t-tab-bar-item wx:for="{{list}}" wx:for-item="item" wx:for-index="index" wx:key="index" > <view class="custom-tab-bar-wrapper"> <t-icon name="{{item.icon}}" size="48rpx" /> <view class="text">{{ item.text }}</view> </view> </t-tab-bar-item> </t-tab-bar>
custom-tab-bar\index.wxss
.custom-tab-bar-wrapper { display: flex; flex-direction: column; align-items: center; } .custom-tab-bar-wrapper .text { font-size: 20rpx; }
3. 解决导航高亮需点击两次的问题
本以为通过以上两步就ok了,结果实际使用时,会发现切换底部导航时,页面切换了,但导航没有变高亮,需要再多点击一次才行……
解决方案如下:
在每个页面的 .js
文件中添加
onShow() { this.getTabBar().init(); },
即在每次页面显示时,对底部导航进行一次初始化。