uni-app–微信小程序自定义tabbar
1.添加 tabBar 代码文件
1) 从官网下载案例,如下:
2) 接着把custom-tab-bar整个文件拷贝到你的项目下:
3) 修改custom-tab-bar/index.js的文件,路径都改为自己uni-app项目下的页面路径和图片路径
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/pages/index/index",
selectedIconPath: "/static/tabs/home-active.png",
iconPath: "/static/tabs/home.png",
text: "首页"
}, {
pagePath: "/pages/message/message",
selectedIconPath: "/static/tabs/message-active.png",
iconPath: "/static/tabs/message.png",
text: "消息"
}
, {
pagePath: "/pages/news/news",
selectedIconPath: "/static/tabs/contact-active.png",
iconPath: "/static/tabs/contact.png",
text: "联系"
}
]
},
attached() {
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
wx.switchTab({url})
this.setData({
selected: data.index
})
}
}
})
4) 修改pages.json文件tabbar配置:主要就是"custom": true这一项
// #ifdef MP-WEIXIN
"tabBar": {
"custom": true,
"color": "#007aff",
"selectedColor": "#ff0000",
"backgroundColor": "#FFFFFF",
"borderStyle":"black",
"list":[
{
"text":"首页",
"pagePath":"pages/index/index",
"iconPath":"static/tabs/home.png",
"selectedIconPath":"static/tabs/home-active.png"
},
{
"text":"消息",
"pagePath":"pages/message/message",
"iconPath":"static/tabs/message.png",
"selectedIconPath":"static/tabs/message-active.png"
},
{
"text":"新闻",
"pagePath":"pages/news/news",
"iconPath":"static/tabs/contact.png",
"selectedIconPath":"static/tabs/contact-active.png"
}
]
},
// #endif
2. 在main.js写入
// #ifdef MP-WEIXIN
Vue.mixin({
methods:{
setTabBarIndex(index) {
if (typeof this.$mp.page.getTabBar === 'function' &&
this.$mp.page.getTabBar()) {
this.$mp.page.getTabBar().setData({
selected: index
})
}
}
}
})
// #endif
3. 在页面中调用setTabBarIndex方法
调用这个方法,主要是解决abbar图标切换 要点击tabbar两次才能有选中状态的问题
联系页面
onShow() {
// #ifdef MP-WEIXIN
this.setTabBarIndex(2);
// #endif
}
消息页面
onShow() {
// #ifdef MP-WEIXIN
this.setTabBarIndex(1);
// #endif
}
首页
onShow() {
// #ifdef MP-WEIXIN
this.setTabBarIndex(0);
// #endif
}