一、選用tabbar組件
在為uniapp應用自定義tabbar之前,我們需要先選用一個tabbar組件。uniapp官方提供的uni-tabbar比較簡單,只有部分樣式可配置,因此我們可以使用其他tabbar組件,比如color-ui等第三方組件。
在使用第三方組件時,我們需要在App.vue中引入組件並設置全局樣式,具體代碼如下:
// 引入組件
import uniTabbar from "@/components/uni-tabbar/uni-tabbar.vue"
export default {
globalData: {},
components: {
uniTabbar // 註冊組件
},
// 設置樣式
onShow() {
uni.setTabBarStyle({
color: "#BFBFBF",
selectedColor: "#0D84FF",
backgroundColor: "#ffffff",
borderStyle: "black",
list: [{
pagePath: "/pages/home/home",
text: "首頁",
iconPath: "/static/tabbar/home.png",
selectedIconPath: "/static/tabbar/home-active.png"
},
{
pagePath: "/pages/personal/personal",
text: "個人中心",
iconPath: "/static/tabbar/personal.png",
selectedIconPath: "/static/tabbar/personal-active.png"
}
]
});
},
};
二、創建自定義tabbar組件
通過uniapp基礎組件提供的基礎功能,我們可以對組件進行擴展,實現自定義tabbar。具體代碼如下:
首頁
個人中心
export default {
data() {
return {
activeIndex: 0 // 當前選中的tab
}
},
methods: {
// 切換tab
switchTab(index) {
this.activeIndex = index
uni.switchTab({
url: this.$refs.tabBar.list[index].pagePath
})
}
}
}
.tabbar {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 50rpx;
background-color: #fff;
border-top: 1rpx solid #e5e5e5;
}
.home,
.personal {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.home.active,
.personal.active {
color: #0D84FF;
}
在創建自定義tabbar組件時,我們需要注意一下每個tab的樣式、切換方法和跳轉路徑等。
三、在頁面使用自定義tabbar組件
當我們創建好自定義tabbar組件後,就可以在需要使用的頁面中引入並使用了。具體代碼如下:
這是首頁
export default {
}
.content {
padding-top: 120rpx;
}
通過引入自定義tabbar組件,在頁面中即可使用。
四、總結
通過以上三個步驟,我們就可以為uniapp應用自定義tabbar了。具體地,我們可以選用第三方tabbar組件,自定義tabbar組件並在需要使用的頁面中引入即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239565.html