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

前言

自定义 tabBar 可以让开发者更加灵活地设置 tabBar 样式,以满足更多个性化的场景,本文分享如何在uniapp vue3 实现自定义微信小程序 tabBar。

配置信息

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

json 复制代码
{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "首页"
      }
    },
    {
      "path": "pages/mine/index",
      "style": {
        "navigationBarTitleText": "我的"
      }
    }
  ],
  "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": "我的"
      }
    ]
  }
}

添加 tabBar 代码文件

在根目录添加 custom-tab-bar 文件夹,下面包含微信小程序原生文件。具体可以参考 微信小程序官方文档

编写 tabBar 代码

这一步需要获取自定义 tabBar 组件实例,通过示例来更新选中的 tab,微信小程序可以通过 this 操作,uniapp 也支持直接操作微信小程序组件示例,如下代码

xml 复制代码
<template>
  <view>
    <text>首页</text>
  </view>
</template>

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

const instance = getCurrentInstance();

onShow(() => {
  const tabBar = instance?.proxy?.$scope?.getTabBar?.();  // 获取组件示例函数返回值
  if (tabBar) {
    tabBar.setData({
      selected: 0,
    });
  }
});
</script>

其他 tab 页同理

示例项目

代码在下方链接的附件

链接

交流群

我建了一个微信群(非官方),大家可以在群里和我沟通交流 uniapp 开发遇到的问题、uniapp 的源码等问题。

相关推荐
2501_933907212 小时前
如何选择性价比高的宁波小程序开发服务公司?
科技·微信小程序·小程序
恋猫de小郭2 小时前
React Native 鸿蒙 2026 路线发布,为什么它的适配成本那么高?
android·前端·react native
呆头鸭L2 小时前
Electron进程通信
前端·javascript·electron·前端框架·vue
splage2 小时前
spring-boot-starter和spring-boot-starter-web的关联
前端
张元清2 小时前
使用 Hooks 构建无障碍 React 组件
前端·javascript·面试
Mahut3 小时前
从零构建神经影像可视化库:neuroviz 的架构设计与实现
前端·javascript·github
慧一居士3 小时前
VueUse 功能介绍使用场景及完整使用示例
前端·vue.js
奇怪的猫3 小时前
浏览器窗口最小化的时候,setInterval 执行变慢,解决方案
前端·javascript
多租户观察室3 小时前
工作流新生态:2026年工作流与Coding的重新分工
前端·人工智能·后端·低代码