当前位置: 首页 > article >正文

解决Vue3+uni-app导航栏高亮自动同步方案

路由跳转自动识别导航高亮实现方法

以下代码使用wd-tabbar组件实现路由跳转时自动同步导航栏高亮状态,适用于所有的Vue3+uni-app项目。 请根据自身使用框架类型完成,也可根据我使用的UI组件进行完成地址如下:

Tabbar 标签栏 | Wot UI ,如需使用请按照Wot UI先进行安装后可直接粘贴复制我的代码!

感谢各位尊敬的VIP用户的支持,如果有帮助到您,还请您给一个宝贵的赞!

<template><view><wd-tabbar fixed v-model="navIndex" bordered safeAreaInsetBottom placeholder shape="round"><wd-tabbar-itemv-for="(item, index) in tabbarList":key="index"@click="navBarRule(index)":title="item.title":icon="item.icon":value="item.value":is-dot="item.isDot"></wd-tabbar-item></wd-tabbar></view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';const navIndex = ref(0);
const tabbarList = ref([{title: '订单中心',icon: 'list',value: 2,isDot: true,path: '/pages/view/order-center/index'},{title: '用户管理',icon: 'user',value: null,isDot: false,path: '/pages/view/user-manager/index'},{title: '数据流水',icon: 'chart-bar',value: null,isDot: false,path: '/pages/view/data-statement/index'},{title: '聊天',icon: 'chat',value: 200,isDot: false,path: '/pages/view/chat/index'},{title: '店主中心',icon: 'app',value: 10,isDot: false,path: '/pages/view/store-owner/index'}
]);const navBarRule = (index: number) => {uni.reLaunch({url: tabbarList.value[index].path});navIndex.value = index;
};const currentRoute = computed(() => {const pages = getCurrentPages();return pages[pages.length - 1]?.route || '';
});navIndex.value = tabbarList.value.findIndex((item) => item.path === `/${currentRoute.value}`
);
</script>

关键实现要点

  • 通过getCurrentPages()获取当前页面栈信息,计算当前路由路径
  • 使用computed属性动态跟踪路由变化
  • 在组件初始化时同步导航栏选中状态
  • 点击导航栏时使用uni.reLaunch进行路由跳转并更新选中状态

注意事项

  • 确保tabbarList中的path与实际路由路径完全匹配
  • 该实现适用于底部导航栏场景,顶部导航需调整样式
  • 使用uni.reLaunch会关闭所有页面并打开新页面,如需保留页面栈可使用uni.navigateTo

该方案已通过实际项目验证,能稳定实现路由与导航栏状态同步。

如果和我的不同情况下,只要您已经完成了导航组件的搭建,在代码中添加

const currentRoute = computed(() => {
  const pages = getCurrentPages();
  return pages[pages.length - 1]?.route || '';
});

navIndex.value = tabbarList.value.findIndex(
  (item) => item.path === `/${currentRoute.value}`
);

这段关键性代码即可,最后需要根据你声明的变量进行替换

http://www.lryc.cn/news/2400821.html

相关文章:

  • DeepSeek+SpringAI实现流式对话
  • 【Spark征服之路-2.1-安装部署Spark(一)】
  • VS代码生成工具ReSharper v2025.1——支持.NET 10和C# 14预览功能
  • 【Godot】如何导出 Release 版本的安卓项目
  • VSCode 工作区配置文件通用模板(CMake + Ninja + MinGW/GCC 编译器 的 C++ 或 Qt 项目)
  • js鼠标事件大全
  • Java八股文——Redis篇
  • 爬虫接口类型判断与表单需求识别全解析
  • Photoshop智能图层 vs 普通图层:核心差异与适用场景对比
  • Chainlink:连接 Web2 与 Web3 的去中心化桥梁
  • [Java 基础]面向对象-继承
  • 编译一个Mac M系列可以用的yuview
  • LeetCode - 876. 链表的中间结点
  • 概率单纯形(Probability Simplex)
  • Go语言爬虫系列教程4:使用正则表达式解析HTML内容
  • 6.4 C++作业
  • rabbitmq Topic交换机简介
  • 网络交换机:构建高效、安全、灵活局域网的基石
  • 【ArcGIS微课1000例】0148:Geographic Imager6.2使用教程
  • 【Oracle】存储过程
  • CppCon 2015 学习A Few Good Types
  • winrm登录失败,指定的凭据被服务器拒绝
  • 单元测试-断言常见注解
  • TDengine 在电力行业如何使用 AI ?
  • Java抽象工厂模式详解
  • matlab实现高斯烟羽模型算法
  • SpringBoot parent依赖高版本覆盖低版本问题
  • OpenCV C/C++ 视频播放器 (支持调速和进度控制)
  • 【Linux庖丁解牛】—自定义shell的编写!
  • C++抽象类与多态实战解析