在一个微信小程序中,需要实现一个功能,点击页面某一个按钮,显示不同底部导航栏,实现效果如下
{{item.text}}
对应js文件,其中list
对应的就是底部导航栏内容
Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
pagePath: "/pages/index/index",
text: "首页",
iconPath: "/images/home.png",
selectedIconPath: "/images/home_b.png"
},
{
pagePath: "/pages/indexcate/indexcate",
text: "发现",
iconPath: "/images/more2.png",
selectedIconPath: "/images/more2_b.png"
},
{
pagePath: "/pages/mycenter/mycenter",
text: "我的",
iconPath: "/images/my.png",
selectedIconPath: "/images/my_b.png"
}
]
},
methods: {
switchTab(e) {
let data = e.currentTarget.dataset
let url = data.path
wx.switchTab({
url
})
this.setData({
selected: data.index
})
}
}
})
onShow
添加对应js代码onShow: function () {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
},
data: {
selected:0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [
{
pagePath: "/shoping/index/index",
text: "首页",
iconPath: "/static/images/tabbar/icon-1.png",
selectedIconPath: "/static/images/tabbar/icon-1-active.png"
},
{
pagePath: "/shoping/shop/caregory/index",
text: "分类",
iconPath: "/static/images/tabbar/icon-2.png",
selectedIconPath: "/static/images/tabbar/icon-2-active.png"
},
{
pagePath: "/shoping/member/cart/index",
text: "购物车",
iconPath: "/static/images/tabbar/icon-4.png",
selectedIconPath: "/static/images/tabbar/icon-4-active.png"
},
{
pagePath: "/shoping/member/index/index",
text: "会员中心",
iconPath: "/static/images/tabbar/icon-5.png",
selectedIconPath: "/static/images/tabbar/icon-5-active.png"
}
]
},
properties: {
selected: {
type: Number,
default:0
}
},
如果不写这个的话,通过switchTab
跳转都会刷新页面,状态都是初始化为默认值了,其中这个selected
来判断是当前那个页面
{
"usingComponents": {
"nav-tabar": "/components/shoping-tabbar/index"
}
}
selected
传递过去首页
以上就是功能所需要的代码,已经上传github了,可以自行下载,在修改修改,优化优化代码,感觉这样写体验效果不是很好,如果有好的方案,可以留言哈