@meng-xi/uni-router 是一个专为 uni-app 开发的路由管理库,采用类似 vue-router 的设计风格,并提供丰富的工具函数,帮助开发者轻松实现跨平台路由管理。
核心功能
- 类 vue-router API:与 vue-router 相似的 API 设计,学习成本低,迁移简单
- 多种导航方式:
- push:保留当前页面的跳转
- replace:替换当前页面
- launch:重启应用并跳转
- tab:切换 tabBar 页面
- go/back:页面返回控制
- 路由守卫:
- beforeEach:导航前执行(适合权限验证)
- afterEach:导航后执行(适合埋点统计)
- 实用方法:
- getCurrentRoute: 获取当前路由信息
- setCustomGetCurrentRoute: 设置自定义获取当前路由的函数
- 实用工具:
- parseLocation:解析路由位置
- buildUrl:构建完整 URL
- getCurrentRoute:获取当前路由
- 全平台适配:完美支持 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: RouteLocationRawPromisereplace替换当前页面location: RouteLocationRawPromiselaunch重启应用跳转location: RouteLocationRawPromisetab切换 tab 页面location: RouteLocationRawPromisego返回指定层数(默认-1)delta?: numbervoidback返回上一页-void路由守卫
方法说明参数返回值beforeEach全局前置守卫guard: NavigationGuardvoidafterEach全局后置钩子hook: AfterEachHookvoid实用方法
方法说明参数返回值getCurrentRoute获取当前路由信息-RouteLocationsetCustomGetCurrentRoute设置自定义获取当前路由的函数customFunction: () => Route | nullvoid实用工具
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(获取失败时)
错误处理
MxRouterError类提供以下静态方法创建错误实例:
navigationAborted
- static navigationAborted(): MxRouterError
复制代码
- 用途:创建导航中止错误(用于前置守卫拦截场景)
- 返回:导航中止错误实例
navigationRedirect
- static navigationRedirect(location: string | RouteLocationRaw): MxRouterError
复制代码
- 用途:创建导航重定向错误(用于路由重定向场景)
- 参数:
- 返回:导航重定向错误实例
navigationFailed
- static navigationFailed(message: string): MxRouterError
复制代码
- 用途:创建导航失败错误(用于导航异常场景)
- 参数:
- 返回:导航失败错误实例
invalidMethod
- static invalidMethod(method: string): MxRouterError
复制代码
- 用途:创建无效方法错误(用于调用非法导航方法场景)
- 参数:
- 返回:无效方法错误实例
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |