@meng-xi/uni-router
@meng-xi/uni-router 是一個專為 uni-app 開發的路由管理庫,采用類似 vue-router 的設計風格,并提供豐富的工具函數,幫助開發者輕松實現跨平臺路由管理。
核心功能
- 類
vue-routerAPI:與vue-router相似的 API 設計,學習成本低,遷移簡單 - 多種導航方式:
push:保留當前頁面的跳轉replace:替換當前頁面launch:重啟應用并跳轉tab:切換 tabBar 頁面go/back:頁面返回控制
- 路由守衛:
beforeEach:導航前執行(適合權限驗證)afterEach:導航后執行(適合埋點統計)
- 實用方法:
getCurrentRoute: 獲取當前路由信息setCustomGetCurrentRoute: 設置自定義獲取當前路由的函數
- 實用工具:
parseLocation:解析路由位置buildUrl:構建完整 URLgetCurrentRoute:獲取當前路由
- Hooks:
useMxRouter:獲取 Router 實例
- 組件:
Router:路由組件
- 全平臺適配:完美支持 H5、小程序和 App
安裝指南
使用 pnpm 安裝:
pnpm install @meng-xi/uni-router
快速入門
初始化路由
import { Router } from '@meng-xi/uni-router'
const router = new Router({
routes: [
{ path: '/home', meta: { title: '首頁' } },
{ path: '/admin', meta: { requiresAuth: true } }
]
})
配置路由守衛
// 認證狀態檢查
const isAuthenticated = () => !!localStorage.getItem('token')
// 前置守衛
router.beforeEach((to, from, next) => {
if (to.meta?.requiresAuth && !isAuthenticated()) {
next({ path: '/login', query: { redirect: to.fullPath } })
} else {
next()
}
})
// 后置鉤子
router.afterEach((to, from) => {
console.log(`從 ${from?.path || '起始頁'} 跳轉到 ${to.path}`)
})
路由跳轉示例
// 基本跳轉
router.push('/products')
// 帶參數跳轉
router.push({
path: '/search',
query: { keyword: '手機' }
})
// 替換當前頁
router.replace('/profile')
// 重啟跳轉
router.launch('/dashboard')
// 切換 tab 頁
router.tab('/tabBar/cart')
// 頁面返回
router.back()
router.go(-2)
單例模式
創建單例
import { Router } from '@meng-xi/uni-router'
Router.getInstance({
routes: [
{ path: '/home', meta: { title: '首頁' } },
{ path: '/admin', meta: { requiresAuth: true } }
]
})
守衛配置
Router.beforeEach((to, from, next) => {
if (to.meta?.requiresAuth && !isAuthenticated()) {
next({ path: '/login', query: { redirect: to.fullPath } })
} else {
next()
}
})
Router.afterEach((to, from) => {
console.log(`路由跳轉: ${from?.path || '起始頁'} → ${to.path}`)
})
導航操作
Router.push('/products')
Router.push({ path: '/search', query: { keyword: '手機' } })
Router.replace('/profile')
Router.launch('/dashboard')
Router.tab('/tabBar/cart')
Router.back()
Router.go(-2)
API 參考
Router 類
實現 RouterInterface 接口,提供核心路由功能。
構造函數
constructor(options?: RouterOptions)
參數說明:
options(可選):包含routes路由配置數組和customGetCurrentRoute自定義獲取當前路由的函數的對象。
導航方法
| 方法 | 說明 | 參數 | 返回值 |
|---|---|---|---|
push |
保留當前頁面的跳轉 | location: RouteLocationRaw |
Promise<void> |
replace |
替換當前頁面 | location: RouteLocationRaw |
Promise<void> |
launch |
重啟應用跳轉 | location: RouteLocationRaw |
Promise<void> |
tab |
切換 tab 頁面 | location: RouteLocationRaw |
Promise<void> |
go |
返回指定層數(默認-1) | delta?: number |
void |
back |
返回上一頁 | - | void |
路由守衛
| 方法 | 說明 | 參數 | 返回值 |
|---|---|---|---|
beforeEach |
全局前置守衛 | guard: NavigationGuard |
void |
afterEach |
全局后置鉤子 | hook: AfterEachHook |
void |
實用方法
| 方法 | 說明 | 參數 | 返回值 |
|---|---|---|---|
getCurrentRoute |
獲取當前路由信息 | - | RouteLocation |
setCustomGetCurrentRoute |
設置自定義獲取當前路由的函數 | customFunction: () => Route | null |
void |
實用工具
parseLocation
parseLocation(location: RouteLocationRaw): { path: string; query?: Record<string, string> }
- 功能:將路由位置信息統一解析為路徑和查詢參數對象
- 參數:
location:支持字符串或對象格式的路由位置信息
- 返回:包含路徑字符串和可選查詢參數的對象
buildUrl
buildUrl(path: string, query?: Record<string, string | number | boolean>): string
- 功能:根據路徑和查詢參數構建完整 URL
- 參數:
path:目標路徑字符串query(可選):查詢參數對象
- 返回:完整的 URL 字符串
getCurrentRoute
getCurrentRoute(currentPage: CurrentPage | null): Route | null
- 功能:獲取當前頁面的路由信息(支持多平臺差異處理)
- 參數:
currentPage:當前頁面實例(可為 null)
- 返回:當前路由對象或 null(獲取失敗時)
Hooks
useMxRouter 用于管理 Router 組件實例并提供操作方法
注意:該 Hook 只支持 vue3 版本
<template>
<mx-router @register="register">首頁</mx-router>
</template>
<script setup lang="ts">
import { useMxRouter } from '@meng-xi/uni-router'
const [register, methods] = useMxRouter({
to: '/pages/index/index'
})
</script>
參數
| 屬性 | 描述 | 類型 | 默認值 |
|---|---|---|---|
| to | 路由地址 | RouterLinkProps | - |
| method | 跳轉方式 | 'push' | 'replace' | 'tab' | 'launch' | 'back' | 'exit' | 'push' |
| delta | 回退層數 | number | - |
| animationType | 窗口動畫類型 | UniApp.NavigateToOptions['animationType'] & UniApp.NavigateBackOptions['animationType'] | pop-in/out |
| animationDuration | 動畫持續時間 | number | 300 |
| renderLink | 是否給 navigator 組件加一層 a 標簽控制 ssr 渲染 | boolean | true |
| hoverClass | 自定義懸停樣式類名 | string | 'none' |
| hoverStopPropagation | 指定是否阻止本節點的祖先節點出現點擊態 | boolean | false |
| hoverStartTime | 按住后多久出現點擊態,單位毫秒 | number | 50 |
| hoverStayTime | 手指松開后點擊態保留時間,單位毫秒 | number | 600 |
| target | 在哪個小程序目標上發生跳轉,值域 self/miniProgram | string | 'self' |
組件
配置
建議使用 easycom 來簡化組件的引入和注冊
NPM
// pages.json
{
"easycom": {
"custom": {
"^mx-(.*)": "@meng-xi/uni-router/components/$1/$1.vue"
}
}
}
HBuilderX
如果你是通過插件市場導入到 HBuilderX 的,需要修改一下組件路徑
// pages.json
{
"easycom": {
"custom": {
"^mx-(.*)": "@/js_sdk/PedroQue99-router/PedroQue99-router/components/$1/$1.vue"
}
}
}
配置全局組件類型
在 vscode 中使用時,為了有組件的類型提示和自動填充,需要配置全局組件類型聲明。
// tsconfig.json
{
"compilerOptions": {
"types": ["@meng-xi/uni-router/components/index"]
}
}
如果是使用 WebStorm,可能需要在 main.ts 文件中導入 index.d.ts 文件。
// main.ts
import '@meng-xi/uni-router/components/index.d.ts'
Router 組件
介紹
Router 組件用于在應用中進行路由導航。它提供了一種聲明式的方式來定義路由鏈接和導航行為。
引入
import Router from '@meng-xi/uni-router/components/router/router.vue'
基礎用法
<template>
<mx-router to="/pages/index/index">首頁</mx-router>
</template>
API
RouterProps
| 屬性 | 描述 | 類型 | 默認值 |
|---|---|---|---|
| to | 路由地址 | RouterLinkProps | - |
| method | 跳轉方式 | 'push' | 'replace' | 'tab' | 'launch' | 'back' | 'exit' | 'push' |
| delta | 回退層數 | number | - |
| animationType | 窗口動畫類型 | UniApp.NavigateToOptions['animationType'] & UniApp.NavigateBackOptions['animationType'] | pop-in/out |
| animationDuration | 動畫持續時間 | number | 300 |
| renderLink | 是否給 navigator 組件加一層 a 標簽控制 ssr 渲染 | boolean | true |
| hoverClass | 自定義懸停樣式類名 | string | 'none' |
| hoverStopPropagation | 指定是否阻止本節點的祖先節點出現點擊態 | boolean | false |
| hoverStartTime | 按住后多久出現點擊態,單位毫秒 | number | 50 |
| hoverStayTime | 手指松開后點擊態保留時間,單位毫秒 | number | 600 |
| target | 在哪個小程序目標上發生跳轉,值域 self/miniProgram | string | 'self' |
RouterSlots
| 插槽 | 描述 | 屬性 |
|---|---|---|
| default | 自定義默認內容 | - |
錯誤處理
MxRouterError類提供以下靜態方法創建錯誤實例:
navigationAborted
static navigationAborted(): MxRouterError
- 用途:創建導航中止錯誤(用于前置守衛攔截場景)
- 返回:導航中止錯誤實例
navigationRedirect
static navigationRedirect(location: string | RouteLocationRaw): MxRouterError
- 用途:創建導航重定向錯誤(用于路由重定向場景)
- 參數:
location:重定向目標位置
- 返回:導航重定向錯誤實例
navigationFailed
static navigationFailed(message: string): MxRouterError
- 用途:創建導航失敗錯誤(用于導航異常場景)
- 參數:
message:錯誤描述信息
- 返回:導航失敗錯誤實例
invalidMethod
static invalidMethod(method: string): MxRouterError
- 用途:創建無效方法錯誤(用于調用非法導航方法場景)
- 參數:
method:無效的方法名稱
- 返回:無效方法錯誤實例

浙公網安備 33010602011771號