乐于分享
好东西不私藏

uniapp 实现微信小程序自定义 tabBar

uniapp 实现微信小程序自定义 tabBar

前言

本文分享如何在 uniapp vue3 实现自定义微信小程序 tabBar,微信小程序自定义 tabBar 官方文档

配置 pages.json

在 pages.json 中添加 tabBar 的相关配置,例如

{
"pages": [
    {
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "首页"
      }
    },
    {
"path": "pages/mine/index",
"style": {
"navigationBarTitleText": "我的"
      }
    },
    {
"path": "pages/detail/index",
"style": {
"navigationBarTitleText": "详情"
      }
    }
  ],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
  },
"tabBar": {
"custom": true,
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [
      {
"pagePath": "pages/index/index",
"iconPath": "static/icon_component.png",
"selectedIconPath": "static/icon_component_HL.png",
"text": "首页"
      },
      {
"pagePath": "pages/mine/index",
"iconPath": "static/icon_API.png",
"selectedIconPath": "static/icon_API_HL.png",
"text": "我的"
      },
      {
"pagePath": "pages/detail/index",
"iconPath": "static/icon_API.png",
"selectedIconPath": "static/icon_API_HL.png",
"text": "详情"
      }
    ]
  }
}

添加 custom-tab-bar

根目录添加 custom-tab-bar 目录,里面写原生微信小程序,这里关键的是 index.js

Component({
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/pages/index/index",
iconPath: "/static/icon_component.png",
selectedIconPath: "/static/icon_component_HL.png",
text: "组件"
        }, {
pagePath: "/pages/mine/index",
iconPath: "/static/icon_API.png",
selectedIconPath: "/static/icon_API_HL.png",
text: "接口"
        }, {
pagePath: "/pages/detail/index",
iconPath: "/static/icon_API.png",
selectedIconPath: "/static/icon_API_HL.png",
text: "详情"
        }]
    },
    attached() {},
methods: {
        switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
            wx.switchTab({
                url
            })
this.setData({
selected: data.index
            })
        }
    }
})

注意:这里的 list 要和 pages.json 中 tabBar 下的 list 一一对应

添加页面

这里以首页为例讲解如果写切换 tab 的逻辑

<template>
<view>
<text>首页</text>
</view>
</template>

<scriptsetup>
import { getCurrentInstance } from"vue";
import { onShow } from"@dcloudio/uni-app";

const instance = getCurrentInstance();

onShow(() => {
const tabBar = instance?.proxy?.$scope?.getTabBar?.();
if (tabBar) {
// 这里的 `0` 对应具体的 tabbar 的下标
    tabBar.setData({
selected: 0,
    });
  }
});
</script>

写在最后

感觉您耐心看完这篇文章,希望您能喜欢。这里是《前端毕业班》,前端开发者的自救互助小组。在 AI 与不确定性并存的时代,我们一起看清焦虑,聊技术、聊趋势,也聊前端还能走多远,走去哪。

相关学习资料