我找了很多很多的文件,大都是显示一级页面的tabbar的,子页面显示tabbar几乎没有,我自己整理了一下。如果有不对的地方,希望评论指出,我会进一步完善。
第一步:要想自定义tabbar,app.json文件中的tabbar对象中加一句 “custom”: true
"tabBar": { "custom": true, **//这一行必填** "color": "#666", "selectedColor": "#57BEAD", "list": [ { "pagePath": "pages/home/home", "text": "主页" }, { "pagePath": "pages/test/test", "text": "测试" } ] }第二步:和pages文件夹同级目录创建一个custom-tab-bar组件,里头写的是tabbar内容 tabbar.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>tabbar.js
Component({ // 组件的属性列表 properties: { // 接受父组件的给的数据 active: { type: "String", value: "" } }, data: { selected: 0, color: "#7A7E83", selectedColor: "#3cc51f", list: [{ "pagePath": "/pages/home/home", "text": "主页" }, { "pagePath": "/pages/test/test", "text": "测试" }] }, attached() { }, methods: { switchTab(e) { if (this.data.selected === e.currentTarget.dataset.index) { return false; } else { const url=e.currentTarget.dataset.path wx.switchTab({url}) } }, run() { console.log(this.data.active); this.setData({ // 通过this.data获取父组件里传过来的值 selected: this.data.active }); console.log(this.data.selected); } } })第三步:一级导航页面
home.js
/** * 生命周期函数--监听页面显示 */ onShow: function () { if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 1 //是你想显示标亮的导航按钮的下标 }) } },第四步:在你要用到的子页面中引入这个组件
子页面.wxml
<tabBar id="tabbar" active="1"></tabBar>/*active是你想显示标亮的导航按钮的下标*/子页面.js
/** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var tabbar = this.selectComponent("#tabbar") // 父组件里面执行子组件的方法 tabbar.run(); },子页面.json
{ "usingComponents": { "tabBar": "/custom-tab-bar/index" }, "navigationBarTitleText": "子页面" }到这边就结束了,接着你哪个页面需要用到这个tabbar,就可以引入,然后传标亮的导航下标就可以了。
