路由器 API
Dojo 路由器提供了一个 API,可用于生成和导航到链接,获取当前路由的参数并检查是否匹配了路由 ID。
link(route: string, params: Params = {}): string | undefined
: 根据路由 ID 和可选参数生成链接。如果未传递参数,它将尝试使用当前路由的参数,然后使用路由配置中提供的任何默认参数。如果无法生成链接,则返回undefined
。setPath(path: string): void
: 在路由器中设置路径。get currentParams(): { [string: index]: string }
: 返回当前路由中的参数getRoute(id: string): RouteContext | undefined
: 如果当前匹配,则返回路由 ID 的RouteContext
。如果未匹配路由 ID,则返回undefined
。
为路由生成链接
src/routes.ts
export default [
{
id: 'home',
path: 'home',
outlet: 'home'
},
{
id: 'about',
path: 'about',
outlet: 'about-overview',
children: [
{
id: 'about-services',
path: '{services}',
outlet: 'about',
defaultParams: {
services: 'sewing'
}
},
{
id: 'about-company',
path: 'company',
outlet: 'about'
},
{
id: 'about-history',
path: 'history',
outlet: 'about'
}
]
}
];
src/main.ts
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// returns `#home`
console.log(router.link('home'));
// returns `#about`
console.log(router.link('about-overview'));
// returns `#about/company`
console.log(router.link('about-company'));
// returns `#about/history`
console.log(router.link('about-history'));
// returns `#about/knitting`
console.log(router.link('about-services'), { services: 'knitting' });
// Uses the current URL then default params to returns `#about/knitting`
// when the current route is `#about/cooking` returns `#about/cooking`
// when the current route does not contain the params returns `#about/sewing`
console.log(router.link('about-services'));
// returns `undefined` for an unknown route
console.log(router.link('unknown'));
更改路由
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// goto `#home` route
router.setPath('#home');
获取当前参数
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// returns the current params for the route
const params = router.currentParams;
获取匹配的路由
使用 getRoute
返回匹配路由 ID 的 RouteContext
,如果路由 ID 的路径未匹配,则返回 undefined
。
RouteContext
:
id: string
: 路由 IDoutlet: string
: 出口 IDqueryParams: { [index: string]: string }
: 来自匹配路由的查询参数。params: { [index: string]: string }
: 来自匹配路由的路径参数。isExact(): boolean
: 一个函数指示路由是否与路径完全匹配。isError(): boolean
: 一个函数指示路由是否与路径的错误匹配。type: 'index' | 'partial' | 'error'
: 路由的匹配类型,可以是index
、partial
或error
。
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// returns the route context if the `home` route is matched, otherwise `undefined`
const routeContext = router.getRoute('home');