【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 的源码等问题。

相关推荐
smallcelebration4 分钟前
151 从0开始搭建后端项目
前端·firefox
wangruofeng6 分钟前
手机和电脑传文件,除了微信还有 LocalSend
前端
excel1 小时前
基于 GPT 的自动发布文章接口方案:从一句话或一张图片生成并发布内容
前端·javascript·后端
其实防守也摸鱼2 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
朱涛的自习室3 小时前
212 个需求、22 万行代码:Agent 接管开源项目的 19 天
android·前端·人工智能
aZhe的全栈知识分享3 小时前
AI 还原 Figma 效果总达不到预期?先别急着让它写代码
前端·后端·面试
review445433 小时前
Codex Hooks 入门实战:生命周期事件、matcher 与5分钟跑通一个钩子
前端·agent·vibecoding
函数小陈3 小时前
阿里云部署DSH与RAM完成运维
前端·后端
用户499335025073 小时前
JS 作用域劫持的死穴:动态 this 穿透,以及 AST 怎么救
前端
IT_陈寒4 小时前
React的setState真是个演员,你以为它同步其实在装睡
前端·人工智能·后端