@basenative /路由器
具有SSR感知路径匹配的基于信号的客户端路由器
部分 BaseNative 生态系统——基于信号的web运行时,基于原生HTML。
安装
npm install @basenative/router
快速入门
import { createRouter, interceptLinks } from '@basenative/router';
const router = createRouter([
{ path: '/', name: 'home' },
{ path: '/users/:id', name: 'user' },
{ path: '/blog/:slug*', name: 'blog' },
]);
// Read reactive current route
import { effect } from '@basenative/runtime';
effect(() => {
const route = router.currentRoute();
console.log(route.name, route.params, route.query);
});
// Navigate programmatically
router.navigate('/users/42');
// Intercept <a> clicks for client-side navigation
interceptLinks(router);
API
createRouter(routes, options?)
创建路由器实例。返回一个对象:
currentRoute-计算信号{ name, path, params, query, matched }.navigate(to, options?)-将新条目推入历史(replace: true改为替换)。back()-导航回浏览器历史记录。forward()-在浏览器历史记录中向前导航。
选项
base-应用于所有路由的路径前缀(例如:'/app')。
resolveRoute(routes, path)
根据路由列表解析路径,而不创建路由器实例。对SSR有用。
compilePattern(pattern)
将路由模式字符串编译为匹配器对象。支持 :param, :param* (通配符) 和精确段。
matchRoute(compiled, path)
针对路径测试已编译的模式。在匹配时返回一个参数对象, null 没有比赛。
parseQuery(search) / buildQuery(params)
将查询字符串解析为对象,或将对象序列化为查询字符串。
interceptLinks(router, options?)
附加一个 click 侦听器到 document ,拦截 <a href> 点击和呼叫 router.navigate() 而不是触发一个完整的页面加载。尊重 target, download和外部链接。
〇航行警卫 @basenative/router/guards
选择- - - - - - createRouter() 它返回的路由器不受影响,除非你包装它。从 /guards 子路径 (也从包根目录重新导出):
import { createRouter } from '@basenative/router';
import { withGuards, redirect } from '@basenative/router/guards';
const router = withGuards(createRouter(routes));
router.beforeEach(({ to, from }) => {
if (to.name === 'dashboard' && !isAuthenticated()) {
return redirect('/login'); // or: return '/login'; or: return false;
}
});
router.afterEach(({ to }) => {
document.title = to.matched?.title ?? 'App';
});
const ok = await router.navigate('/dashboard'); // Promise<boolean>
withGuards(router)
包装路由器实例 (从 createRouter()),并返回 GuardedRouter 与相同的 pathname / query / currentRoute / back() / forward() / routes,再加上:
navigate(to, options?)-与封装的路由器相同,但返回Promise<boolean>:true一次导航和所有afterEach处理程序已运行,false如果警卫中止或重定向。beforeEach(guard)-注册防护,在URL更改之前,针对目标路由的预览按注册顺序运行。返回取消注册它的处置器。afterEach(handler)-注册一个调用的处理程序{ to, from, options }) 一旦导航提交。返回一个处置器。
一名警卫接到 { to, from, options } (to/from 是 ResolvedRoute秒; from 是 null 在第一次导航时),并可能返回:
undefined/什么都不做——让导航继续进行。false-没有重定向的中止导航。- 路径字符串,或
{ redirect, replace? }-中止并重定向到该路径。 - 扔
redirect(to, replace?)(或RedirectError直接)-与上述相同,可从防护装置内部深处使用。 - 抛出其他任何东西——传播并拒绝
navigate()调用; 它不被视为中止。
守卫按顺序运行; 第一个中止的守卫停止链-以后的守卫不运行。开始一个新的 navigate() 在前一个警卫仍在运行时呼叫中止正在进行的呼叫,然后解决 false.
redirect(to, replace = true)
抛出一个 RedirectError 那 withGuards()他的后卫跑垒手接住了球,转了个方向。从来没有回报。
RedirectError
错误类 redirect() 抛出。有 to: string 和 replace: boolean 属性;也可以直接用扔 throw new RedirectError(to, replace).
许可证
apache - 2.0