找回密码
 立即注册
首页 资源区 代码 @meng-xi/uni-router

@meng-xi/uni-router

梨恐 前天 17:03
@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 安装:
  1. pnpm install @meng-xi/uni-router
复制代码
快速入门

初始化路由
  1. import { Router } from '@meng-xi/uni-router'
  2. const router = new Router({
  3.         routes: [
  4.                 { path: '/home', meta: { title: '首页' } },
  5.                 { path: '/admin', meta: { requiresAuth: true } }
  6.         ]
  7. })
复制代码
配置路由守卫
  1. // 认证状态检查
  2. const isAuthenticated = () => !!localStorage.getItem('token')
  3. // 前置守卫
  4. router.beforeEach((to, from, next) => {
  5.         if (to.meta?.requiresAuth && !isAuthenticated()) {
  6.                 next({ path: '/login', query: { redirect: to.fullPath } })
  7.         } else {
  8.                 next()
  9.         }
  10. })
  11. // 后置钩子
  12. router.afterEach((to, from) => {
  13.         console.log(`从 ${from?.path || '起始页'} 跳转到 ${to.path}`)
  14. })
复制代码
路由跳转示例
  1. // 基本跳转
  2. router.push('/products')
  3. // 带参数跳转
  4. router.push({
  5.         path: '/search',
  6.         query: { keyword: '手机' }
  7. })
  8. // 替换当前页
  9. router.replace('/profile')
  10. // 重启跳转
  11. router.launch('/dashboard')
  12. // 切换 tab 页
  13. router.tab('/tabBar/cart')
  14. // 页面返回
  15. router.back()
  16. router.go(-2)
复制代码
单例模式

创建单例
  1. import { Router } from '@meng-xi/uni-router'
  2. Router.getInstance({
  3.         routes: [
  4.                 { path: '/home', meta: { title: '首页' } },
  5.                 { path: '/admin', meta: { requiresAuth: true } }
  6.         ]
  7. })
复制代码
守卫配置
  1. Router.beforeEach((to, from, next) => {
  2.         if (to.meta?.requiresAuth && !isAuthenticated()) {
  3.                 next({ path: '/login', query: { redirect: to.fullPath } })
  4.         } else {
  5.                 next()
  6.         }
  7. })
  8. Router.afterEach((to, from) => {
  9.         console.log(`路由跳转: ${from?.path || '起始页'} → ${to.path}`)
  10. })
复制代码
导航操作
  1. Router.push('/products')
  2. Router.push({ path: '/search', query: { keyword: '手机' } })
  3. Router.replace('/profile')
  4. Router.launch('/dashboard')
  5. Router.tab('/tabBar/cart')
  6. Router.back()
  7. Router.go(-2)
复制代码
API 参考

Router 类

实现 RouterInterface 接口,提供核心路由功能。
构造函数
  1. 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
  1. parseLocation(location: RouteLocationRaw): { path: string; query?: Record<string, string> }
复制代码

  • 功能:将路由位置信息统一解析为路径和查询参数对象
  • 参数

    • location:支持字符串或对象格式的路由位置信息

  • 返回:包含路径字符串和可选查询参数的对象
buildUrl
  1. buildUrl(path: string, query?: Record<string, string | number | boolean>): string
复制代码

  • 功能:根据路径和查询参数构建完整 URL
  • 参数

    • path:目标路径字符串
    • query(可选):查询参数对象

  • 返回:完整的 URL 字符串
getCurrentRoute
  1. getCurrentRoute(currentPage: CurrentPage | null): Route | null
复制代码

  • 功能:获取当前页面的路由信息(支持多平台差异处理)
  • 参数

    • currentPage:当前页面实例(可为 null)

  • 返回:当前路由对象或 null(获取失败时)
错误处理

MxRouterError类提供以下静态方法创建错误实例:
navigationAborted
  1. static navigationAborted(): MxRouterError
复制代码

  • 用途:创建导航中止错误(用于前置守卫拦截场景)
  • 返回:导航中止错误实例
navigationRedirect
  1. static navigationRedirect(location: string | RouteLocationRaw): MxRouterError
复制代码

  • 用途:创建导航重定向错误(用于路由重定向场景)
  • 参数

    • location:重定向目标位置

  • 返回:导航重定向错误实例
navigationFailed
  1. static navigationFailed(message: string): MxRouterError
复制代码

  • 用途:创建导航失败错误(用于导航异常场景)
  • 参数

    • message:错误描述信息

  • 返回:导航失败错误实例
invalidMethod
  1. static invalidMethod(method: string): MxRouterError
复制代码

  • 用途:创建无效方法错误(用于调用非法导航方法场景)
  • 参数

    • method:无效的方法名称

  • 返回:无效方法错误实例

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册