全网并没有找到一篇可自定义图标的tabbar。
又都是复制的。。。
哎,于是我就来首发第一篇
首先在app.json
"tabBar": { "custom": true, "list": [ { "text": "天气", "pagePath": "pages/index/index" }, { "text": "空气质量", "pagePath": "pages/quality/index" }, { "text": "生活建议", "pagePath": "pages/logs/logs" } ] },
在根目录创建custom-tab-bar创建以下文件
- index.js
- index.json
- index.wxss
- index.wxml
在index.js写上如下参照代码
这里用到了云存储,链接请自行替换
Component({ data: { active:0, list:[{ text:"天气", normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/weather_normal.png", active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/weather_select.png", url:"/pages/index/index" }, { text:"空气质量", normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/quality_normal.png", active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/quality_select.png", url:"/pages/quality/index" }, { text:"生活建议", normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/advice_normal.png", active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/advice_select.png", url:"/pages/logs/logs" }, ] }, methods: { onChange:function(e){ const i = e.detail; wx.switchTab({ url: this.data.list[i].url, }) this.setData({ active : i }) }, init() { const page = getCurrentPages().pop(); this.setData({ active: this.data.list.findIndex(item => item.url === `/${page.route}`) }); } } })
在index.json引用组件
{ "component": true, "usingComponents": { "van-tabbar": "/miniprogram/miniprogram_npm/@vant/weapp/tabbar/index", "van-tabbar-item": "/miniprogram/miniprogram_npm/@vant/weapp/tabbar-item/index" } }
在index.wxml,实际上举一反三很简单,只要wx-for循环而已
<van-tabbar active="{{ active }}" active-color="#63bce9" inactive-color="#000" bind:change="onChange"> <van-tabbar-item wx:for="{{list}}" wx:key="index"> <image slot="icon" src="{{ item.normal }}" mode="aspectFit" style="width: 30px; height: 18px;" /> <image slot="icon-active" src="{{ item.active }}" mode="aspectFit" style="width: 30px; height: 18px;" /> {{item.text}} </van-tabbar-item> </van-tabbar>
在使用的页面,例如pages/index/index.js增加生命周期函数,实现高亮
onShow: function () { this.getTabBar().init(); },
大功告成了!