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

解决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.xdnf.cn/news/10616.html

相关文章:

  • 什么是C语言块级变量
  • 使用NMEA Tools生成GPS轨迹图
  • 湖北理元理律所:企业债务重组中的“法律缓冲带”设计
  • 重温经典算法——堆排序
  • 九(1). 引用作为函数参数的使用
  • DDR5舍入定义和算法Rounding Definitions and Algorithms详细讲解
  • 第17讲、odoo18可视化操作代码生成模块
  • L2-054 三点共线 - java
  • 【LeetCode】数组|枚举|数学题型刷题汇总
  • 头像预览和上传
  • 第一章:计算机系统概论
  • Y1——链式前向星
  • 在 Linux 服务器上无需 sudo 权限解压/打包 .7z 的方法(实用命令)
  • 21-CS61B-lab6:java文件操作以及持久化一见
  • BiliNote简介
  • 第100期 DL,多输入多输出通道
  • 学习STC51单片机25(芯片为STC89C52RCRC)
  • edg浏览器打开后默认是360界面
  • 某电子计数跳绳的一次修复经历
  • abandon便签:一个免费好用审美在线的桌面便签应用
  • python打卡day43
  • 【Python序列化】TypeError: Object of type xxx is not JSON serializable问题的解决方案
  • 分词算法BBPE详解和Qwen的应用
  • day 40 python打卡
  • Spring框架学习day6--事务管理
  • 【ISAQB大纲解读】信息隐藏指的是什么
  • 基于Qt的app开发的过渡期
  • PH热榜 | 2025-06-01
  • Flex弹性布局
  • langGraph多Agent