uniapp实现自定义底部tab栏

1、自定义底部导航组件接收一个tabs数组作为参数,每个数组项包含icontext字段,用于表示每个底部标签的图标和文本。通过遍历tabs数组,渲染每个底部标签项的图标和文本。activeIndex表示当前选中的底部标签的索引。点击底部标签时,调用switchTab方法切换底部导航,并通过$emit触发switchTab事件,将选中的标签索引传递给父组件。

复制代码
<template>  
     <view class="custom-tab-bar">  
       <view class="tab-bar-item" v-for="(item, index) in tabs" :key="index" :class="{ active: activeIndex === index }" @click="switchTab(index)">  
         <!-- 图标 -->  
         <image :src="item.icon" class="tab-bar-icon"></image>  
         <!-- 文字 -->  
         <text>{{ item.text }}</text>  
       </view>  
     </view>  
   </template>  
     
   <script>  
   export default {  
     props: {  
       tabs: {  
         type: Array,  
         default: () => []  
       },  
       activeIndex: {  
         type: Number,  
         default: 0  
       }  
     },  
     methods: {  
       switchTab(index) {  
         // 切换底部导航  
         this.$emit("switchTab", index);  
       }  
     }  
   };  
   </script>  
     
   <style scoped>  
   .custom-tab-bar {  
     display: flex;  
     justify-content: space-around;  
     align-items: center;  
     height: 50px;  
     background-color: #fff;  
   }  
     
   .custom-tab-bar .tab-bar-item {  
     display: flex;  
     flex-direction: column;  
     align-items: center;  
     font-size: 12px;  
   }  
     
   .custom-tab-bar .tab-bar-item.active {  
     color: #007aff;  
   }  
     
   .custom-tab-bar .tab-bar-icon {  
     width: 24px;  
     height: 24px;  
     margin-bottom: 4px;  
   }  
   </style>

2、在需要显示自定义底部导航的页面中,引入和使用自定义底部导航组件。例如,在pages文件夹下的home页面中,可以添加以下代码:

复制代码
<template>  
     <view>  
       <!-- 页面内容... -->  
     </view>  
     <!-- 引入自定义底部导航 -->  
     <custom-tab-bar :tabs="tabs" :activeIndex="activeTab" @switchTab="switchTab"></custom-tab-bar>  
   </template>  
     
   <script>  
   import CustomTabBar from "@/components/CustomTabBar";  
   export default {  
     components: {  
       CustomTabBar  
     },  
     data() {  
       return {  
         tabs: [  
           { icon: "icon-home", text: "首页" },  
           { icon: "icon-category", text: "分类" },  
           { icon: "icon-cart", text: "购物车" },  
           { icon: "icon-mine", text: "我的" }  
         ],  
         activeTab: 0  
       };  
     },  
     methods: {  
       switchTab(index) {  
         // 切换底部导航  
         this.activeTab = index;  
         // 根据索引进行相应的页面切换或逻辑处理  
         // ...  
       }  
     }  
   };  
   </script>
相关推荐
很晚很晚了2 小时前
纯前端转全栈 Day 1:我从第一个 NestJS 接口开始
前端
Lee川3 小时前
从零解剖一个 AI Agent Tool是如何实现的
前端·人工智能·后端
wangruofeng4 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
李白的天不白6 小时前
SSR服务端渲染
前端
卷帘依旧7 小时前
SSE(Server-Sent Events)完全指南
前端
码云之上7 小时前
万星入坞:我们如何用三层插件体系干掉巨石应用
前端·架构·前端框架
kyriewen7 小时前
一口气讲清楚 Monorepo、Turborepo、pnpm、Changesets 到底是什么?
前端·架构·前端工程化
IT_陈寒8 小时前
React性能优化踩的坑,这个错你可能也会犯
前端·人工智能·后端
zhangxingchao8 小时前
AI应用开发三:RAG技术与应用
前端·人工智能·后端
摘星小杨9 小时前
如何在前端循环调取接口,实时查询数据
开发语言·前端·javascript