TSone

路由 API

TSone 路由以插件形式安装,并通过 RouterView 渲染当前路由组件。

createRouter

名称签名说明
createRoutercreateRouter(options: RouterOptions | RouteRecord[]): Router创建路由实例并返回可安装插件。
RouterViewclass RouterView extends Component渲染当前路由匹配到的组件。
RouterLinkclass RouterLink extends Component<RouterLinkProps>渲染可拦截点击并通过路由导航的链接。
import { createRouter } from '@geektech/tsone/router';

const router = createRouter({
  mode: 'history',
  base: '/',
  routes: [
    { path: '/', name: 'home', component: HomePage },
    { path: '/users/:id', name: 'user', component: UserPage, meta: { title: '用户详情' } },
  ],
});

最小配置可以写成 createRouter({ routes: [...] })。

导航守卫、重定向与通配路由

router.beforeEach(guard) 注册全局前置守卫:返回 false 取消导航,返回字符串重定向到该路径,返回 true 或 undefined 放行;router.afterEach(hook) 在导航提交后调用。守卫仅在编程式导航(push/replace)时执行。RouteRecord.redirect 让路由解析到目标路径(防循环);path: '*' 匹配所有未命中路径,剩余路径通过 params.pathMatch 获取。

import { createRouter } from '@geektech/tsone/router';

const router = createRouter({
  routes: [
    { path: '/', component: HomePage },
    { path: '/old', redirect: '/new' },
    { path: '/new', component: NewPage },
    { path: '*', component: NotFoundPage },
  ],
});

router.beforeEach((to, from) => {
  if (to.path === '/admin') return false;
  return true;
});
router.afterEach((to) => {
  document.title = String(to.meta?.title ?? '');
});

RouterOptions

interface RouterOptions {
  routes: RouteRecord[];
  mode?: 'history' | 'hash';
  base?: string;
}

RouteRecord

interface RouteRecord {
  path: string;
  component?: ComponentConstructor;
  redirect?: string;
  name?: string;
  meta?: Record<string, unknown>;
}

path 支持动态参数,例如 /users/:id。

RouterView

import { Component, VNode } from '@geektech/tsone';
import { RouterView } from '@geektech/tsone/router';

class Layout extends Component<object, object> {
  protected initState() {
    return {};
  }

  protected initStyles(): void {}

  protected render(): VNode {
    return {
      tag: 'main',
      children: [{ component: RouterView }],
    };
  }
}

RouterLink

import { RouterLink } from '@geektech/tsone/router';

{
  component: RouterLink,
  props: {
    to: '/users/42',
    activeClass: 'is-active',
    children: ['用户详情'],
  },
}

RouterLink 会生成 a 标签,点击后调用 router.push() 或 router.replace()。

Router 方法

  • push(path) / replace(path): 导航到新路径
  • back() / forward() / go(n): 操作浏览器历史记录
  • getCurrentRoute(): 返回当前路由位置
  • getCurrentRouteRecord(): 返回当前匹配到的路由记录
  • onRouteChange(callback): 注册路由变化监听
  • addRoute(record): 动态添加路由
  • createHref(path): 根据模式与 base 生成链接地址
  • destroy(): 移除事件监听并解除应用上的路由引用