@tker/router
v2.0.2
Published
基于 Vue Router 的路由管理器封装,提供单例模式、简化的 API 和拦截器支持。
Downloads
355
Readme
@tker/router
基于 Vue Router 的路由管理器封装,提供单例模式、简化的 API 和拦截器支持。
安装
pnpm add @tker/router vue-router基本用法
初始化
//router/index.ts
import type { App } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { createRouter } from "@tker/router";
const routes:RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('./views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('./views/About.vue')
}
]
export const setupRouter = (app: App) => {
const router = createRouter();
router.addRoutes(routes);
router.addBeforeInterceptor((to, from) => {
console.log("beforeEnter", from, to);
return true;
});
router.addAfterInterceptor((to, from) => {
console.log("afterEnter", from, to);
});
app.use(router.getRouter());
};
//main.ts
import { createApp } from "vue";
import { setupRouter } from "./router";
const app = createApp(App);
setupRouter(app);
app.mount("#app");路由模式
支持三种路由模式:
| 模式 | 说明 | URL 示例 |
|------|------|----------|
| history | HTML5 History 模式(默认) | https://example.com/user |
| hash | Hash 模式 | https://example.com/#/user |
| memory | 内存模式(不改变 URL) | 适用于非浏览器环境 |
// History 模式
createRouter({ mode: 'history' })
// Hash 模式
createRouter({ mode: 'hash' })
// 内存模式
createRouter({ mode: 'memory' })API 参考
配置选项
RouterSetupOptions
interface RouterSetupOptions {
baseRoot?: string // 基础路径,默认 '.'
history?: RouterHistory // 自定义 history 实例(优先级高于 mode)
mode?: 'hash' | 'history' | 'memory' // 路由模式,默认 'history'
}初始化方法
createRouter(options?)
创建或获取路由管理器实例(单例模式)。
import { createRouter } from '@tker/router'
const manager = createRouter({
mode: 'history',
baseRoot: '/'
})导航方法
push(to)
路由跳转,支持字符串和对象两种形式。返回 Promise,可用于错误处理。
import { push } from '@tker/router'
// 字符串路径
push('/user/profile')
// 对象形式
push({ name: 'UserProfile' })
push({ path: '/user', query: { id: '123' } })
push({ name: 'User', params: { id: '123' } })
// 错误处理
try {
await push('/some-route')
} catch (e) {
console.error('导航失败', e)
}replace(to)
路由替换(不保留历史记录)。返回 Promise。
import { replace } from '@tker/router'
replace('/login')
replace({ name: 'Home' })
// 错误处理
await replace('/dashboard')go(delta)
前进/后退指定步数。
import { go } from '@tker/router'
go(-1) // 后退一步
go(2) // 前进两步back()
后退一步。
import { back } from '@tker/router'
back()forward()
前进一步。
import { forward } from '@tker/router'
forward()路由管理
addRoutes(routes)
动态添加路由配置。
import { addRoutes } from '@tker/router'
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/admin',
name: 'Admin',
component: () => import('./views/Admin.vue')
}
]
addRoutes(routes)getRouter()
获取 Vue Router 实例。
import { getRouter } from '@tker/router'
const router = getRouter()
// 可以访问 Vue Router 的完整 API
const currentRoute = router.currentRoutegetCurrentRoute()
获取 Vue Router currentRoute。
import { getCurrentRoute } from '@tker/router'
const currentRoute = getCurrentRoute()
// 通过 currentRoute.value 访问
const path = currentRoute.value.fullPathdestroy()
销毁路由管理器,清理拦截器并重置单例。可用于测试或热重载场景。
import { destroy, createRouter } from '@tker/router'
// 销毁后可以重新初始化
destroy()
createRouter({ mode: 'hash' })拦截器
addBeforeInterceptor(interceptor)
添加前置拦截器,在路由跳转前执行。返回 false 可阻止跳转。
import { addBeforeInterceptor } from '@tker/router'
// 权限验证示例
addBeforeInterceptor(async (to, from) => {
const isLoggedIn = await checkAuth()
if (to.name === 'Admin' && !isLoggedIn) {
push('/login')
return false // 阻止跳转
}
return true // 允许跳转
})addAfterInterceptor(interceptor)
添加后置拦截器,在路由跳转后执行。
import { addAfterInterceptor } from '@tker/router'
// 页面访问统计示例
addAfterInterceptor((to, from) => {
trackPageView(to.fullPath)
})类型定义
// 前置拦截器类型
type RouterBeforeInterceptor = (
to: RouteLocationNormalized,
from: RouteLocationNormalized
) => boolean | Promise<boolean>
// 后置拦截器类型
type RouterAfterInterceptor = (
to: RouteLocationNormalized,
from: RouteLocationNormalized
) => Promise<void> | void
// 路由跳转参数
type RouterPushPayload =
| string
| {
name?: string
params?: Record<string, any>
path?: string
query?: Record<string, any>
}完整示例
// main.ts
import { createApp } from 'vue'
import {
createRouter,
addRoutes,
addBeforeInterceptor,
getRouter,
push
} from '@tker/router'
import App from './App.vue'
// 1. 初始化路由管理器
createRouter({ mode: 'history' })
// 2. 添加路由配置
addRoutes([
{ path: '/', name: 'Home', component: () => import('./views/Home.vue') },
{ path: '/login', name: 'Login', component: () => import('./views/Login.vue') },
{ path: '/dashboard', name: 'Dashboard', component: () => import('./views/Dashboard.vue') }
])
// 3. 添加前置拦截器(权限控制)
addBeforeInterceptor(async (to, from) => {
const publicPages = ['Home', 'Login']
if (publicPages.includes(to.name as string)) {
return true
}
const isLoggedIn = await checkAuth()
if (!isLoggedIn) {
push({ name: 'Login' })
return false
}
return true
})
// 4. 获取并挂载路由
const app = createApp(App)
app.use(getRouter()!)
app.mount('#app')License
MIT
