您现在的位置是:首页 >技术教程 >原生wx小程序用vant组件自定义底部导航网站首页技术教程
原生wx小程序用vant组件自定义底部导航
简介原生wx小程序用vant组件自定义底部导航
1.在根目录中创建custom-tab-bar,新建page index
2.在app.json
或index.json
中引入vant组件
"usingComponents": { "van-tabbar": "@vant/weapp/tabbar/index", "van-tabbar-item": "@vant/weapp/tabbar-item/index" }
index.wxss
/* custom-tab-bar/index.wxss */ .custom-tab-bar-wrapper { display: flex; flex-direction: column; align-items: center; } .custom-tab-bar-wrapper .text { font-size: 24rpx; } .custom-tab-bar-wrapper .tab-icon { width: 40rpx; height: 40rpx; } .custom-tabbar-item { width: 100% !important; } .imageIcon{ width: 50rpx; height: 50rpx; }
index.wxml
<van-tabbar active="{{ active }}" bind:change="onChange" inactive-color="#333333" active-color="#1479FF" > <van-tabbar-item class="custom-tab-bar-wrapper" custom-class="custom-tabbar-item" wx:for="{{list}}" wx:key="index"> <image slot="icon" src="{{ item.iconPath }}" mode="aspectFit" class="imageIcon" /> <image slot="icon-active" src="{{ item.selectedIconPath }}" mode="aspectFit" class="imageIcon" /> <view class="text">{{ item.text }}</view> </van-tabbar-item> </van-tabbar>
index.js
// custom-tab-bar/index.js Component({ data: { active: 0, list: [ { pagePath: "pages/home/index", text: "首页", iconPath: "/static/images/home.png", selectedIconPath: "/static/images/home_active.png" }, { pagePath: "pages/diagnosis/index", text: "分类", iconPath: "/static/images/classify.png", selectedIconPath: "/static/images/classify_active.png" }, { pagePath: "pages/personal_center/index", text: "我的", iconPath: "/static/images/personal.png", selectedIconPath: "/static/images/personal_active.png" } ] }, methods: { onChange(event) { // 切换tab页面 this.setData({ active: event.detail }); // console.log(this.data.list[event.detail].pagePath) wx.switchTab({ url: this.data.list[event.detail].pagePath.startsWith('/') ? this.data.list[event.detail].pagePath : `/${this.data.list[event.detail].pagePath}`, }); }, init() { // 设置tab的active下标(icon) const page = getCurrentPages().pop(); const route = page ? page.route.split('?')[0] : ''; const active = this.data.list.findIndex( (item) => (item.pagePath.startsWith('/') ? item.pagePath.substr(1) : item.pagePath) === `${route}`, ); this.setData({ active }); }, }, });
app.json
"tabBar": { "custom": true, "color": "#333", "selectedColor": "#333333", },
在tab页中的onShow()
/** * 生命周期函数--监听页面显示 */ onShow() { this.getTabBar().init() // 设置tabbar active状态 },
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。