1.   目录结构必须按照如图所示,在src 目录下 

 2. index.js

Component({
	data: {
		selected: 0,
		color: '#7A7E83',
		selectedColor: '#3cc51f',
		list: [
			{
				pagePath: '/pages/index/index',
				iconPath: '/static/tabbar/index.png',
				selectedIconPath: '/static/tabbar/index_selected.png',
				text: '首页'
			},
			{
				pagePath: '/pages/mine/index',
				iconPath: '/static/tabbar/mine.png',
				selectedIconPath: '/static/tabbar/mine_selected.png',
				text: '我的'
			}
		]
	},
	attached() {},
	methods: {
		switchTab(e) {
			const data = e.currentTarget.dataset
			if (data.index === this.data.selected) {
				return
			}
			const url = data.path
			wx.switchTab({ url })
			this.setData({
				selected: data.index
			})
		}
	}
})

3.  index.html

<view class="tabBar">
    <view class="border"></view>
    <view wx:for="{{list}}" wx:key="index" class="tabBarItem" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
        <image class="image" src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image>
        <view class="text" style="color: {{selected === index ? selectedColor : color}}">
            {{item.text}}
        </view>
    </view>
</view>

4.  wxss

.tabBar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 99;
	height: 50px;
	background: white;
	display: flex;
	padding-bottom: env(safe-area-inset-bottom);
}

.border {
	background-color: rgba(0, 0, 0, 0.2);
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	height: 1rpx;
	z-index: 2;
	transform: scaleY(0.5);
}

.tabBarItem {
	flex: 1;
	text-align: center;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
}

.tabBarItem .image {
	width: 20px;
	height: 20px;
	margin-bottom: 4px;
}

.tabBarItem .text {
	font-size: 12px;
}

5. index.json

{
	"component": true
}

 按照微信官方文档,以及代码片段,需要在tabbar 页面中onshow生命周期内设置 tabbar 的选中状态,但是在 uniapp 创建的 页面中是 this 是不包含 getTabBar 方法的, 只有通过 this.$mp.page或者 this.$scope 可以获取到

async onShow() {
		if (typeof this.$mp.page.getTabBar === 'function' &&                 this.$mp.page.getTabBar()) {
			console.log(this)
			this.$mp.page.getTabBar().setData({
				selected: 0
			})
		}
	},
async onShow() {
		if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) {
			console.log(this)
			this.$scope.getTabBar().setData({
				selected: 0
			})
		}
	},

通过设置当前页面下的 tabbar 选中状态,自定义tabbar才能正常使用

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐