路由跳轉自動識別導航高亮實現方法
以下代碼使用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}`
);這段關鍵性代碼即可,最后需要根據你聲明的變量進行替換