浏览代码

fix(tabbar): 修复设置tabbar角标时的潜在越界问题

在设置tabbar角标前添加数组越界检查,防止当idx超出tabbarList范围时报错
feige996 8 月之前
父节点
当前提交
eafd3a9f30
共有 2 个文件被更改,包括 12 次插入1 次删除
  1. 9 0
      src/pages/about/about.vue
  2. 3 1
      src/tabbar/store.ts

+ 9 - 0
src/pages/about/about.vue

@@ -9,6 +9,7 @@
 
 <script lang="ts" setup>
 import { LOGIN_PAGE } from '@/router/config'
+import { tabbarStore } from '@/tabbar/store'
 import RequestComp from './components/request.vue'
 
 // 奇怪:同样的代码放在 vue 里面不会校验到错误,放在 .ts 文件里面会校验到错误
@@ -54,6 +55,11 @@ function gotoTabbar() {
     url: '/pages/index/index',
   })
 }
+// #region setTabbarBadge
+function setTabbarBadge() {
+  tabbarStore.setTabbarItemBadge(3, 10)
+}
+// #endregion
 </script>
 
 <template>
@@ -67,6 +73,9 @@ function gotoTabbar() {
     <button class="mt-4 w-40 text-center" @click="toLogin">
       点击去登录页
     </button>
+    <button class="mt-4 w-60 text-center" @click="setTabbarBadge">
+      设置tabbarBadge
+    </button>
     <RequestComp />
     <view class="mb-6 h-1px bg-#eee" />
     <view class="text-center">

+ 3 - 1
src/tabbar/store.ts

@@ -36,7 +36,9 @@ const tabbarStore = reactive({
     uni.setStorageSync('app-tabbar-index', idx)
   },
   setTabbarItemBadge(idx: number, badge: CustomTabBarItemBadge) {
-    tabbarList[idx].badge = badge
+    if (tabbarList[idx]) {
+      tabbarList[idx].badge = badge
+    }
   },
   setAutoCurIdx(path: string) {
     const index = tabbarList.findIndex(item => item.pagePath === path)