1.前言
在uniapp中我们需要自定义tabbar,而不去使用pages.json内的tabbar配置项。
2.版本
uniapp vue3版本
3.过程
3.1.修改pages.json
找到pages.json文件,删除pathPath以外的属性。
"tabBar": {
"list": [{
"pagePath": "pages/home/home"
},
{
"pagePath": "pages/my/my"
}
]
},
3.2.隐藏原生tabbar并添加全局变量tabbarIndex
<script setup>
import { onLaunch, } from "@dcloudio/uni-app";
getApp().globalData = {
tabbarIndex: 0,
};
onLaunch(() => {
uni.hideTabBar();
});
</script>
3.3.创建tabbar组件
<template>
<view class="tabBarRow">
<view
v-for="(item, index) in list"
:key="index"
:class="['tabBarItem', index == tabbarIndex ? 'selctedIcon' : 'icon']"
@click="changeTabBar(index)"
>
<image :src="index == tabbarIndex ? item.selectedIcon : item.icon"></image>
</view>
</view>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
const tabbarIndex = ref(getApp().globalData.tabbarIndex);//获取全局变量tabbarIndex
const list = reactive([
{
label: "首页",
path: "/pages/home/home",
icon: "/static/tabbar/home_icon.png",
selectedIcon: "/static/tabbar/home_icon_selected.png",
},
{
label: "我的",
path: "/pages/my/my",
icon: "/static/tabbar/my_icon.png",
selectedIcon: "/static/tabbar/my_icon_selected.png",
},
]);
function changeTabBar(index) {
console.log("changeTabBar", index);
getApp().globalData.tabbarIndex = index; //切换菜单时修改全局变量tabbarIndex
uni.switchTab({
url: list[index].path,
});
}
</script>
<style scoped>
.tabBarRow {
flex-direction: row;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
align-items: center;
justify-items: center;
width: 100%;
height: 124rpx;
background-color: white;
position: fixed;
bottom: 0;
z-index: 999;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
/* padding-bottom: 40rpx */
}
.tabBarItem {
height: 100rpx;
width: 100rpx;
position: relative;
top: -24rpx;
}
.selctedIcon {
height: 146rpx;
width: 146rpx;
}
.icon {
height: 96rpx;
width: 96rpx;
}
.tabBarItem image {
height: 100%;
width: 100%;
}
</style>
3.4.在所有菜单中引入tabbar组件
<template>
<tabbar></tabbar>
</template>
<script setup lang="ts">
import tabbar from "@/components/tabbar/tabbar.vue";
</script>
4.结尾
这样就完成了uniapp的自定义tabbar组件了。