Guide
路由系统
TSone 内置了路由系统,用于通过不同 URL 路径显示不同内容。
核心概念
路由实例
路由实例通过 createRouter 创建,负责管理路由配置和导航。
路由配置
路由配置是一组 RouteRecord,定义路径与组件之间的映射关系。
路由导航
您既可以编程式导航,也可以通过 RouterLink 进行声明式导航。
基本使用
安装路由
import { createRouter, RouterLink, RouterView } from '@geektech/tsone/router';创建路由实例
import { createApp } from '@geektech/tsone';
import { createRouter, RouterView } from '@geektech/tsone/router';
const router = createRouter({
routes: [
{ path: '/', name: 'home', component: HomeComponent, meta: { title: '首页' } },
{ path: '/about', name: 'about', component: AboutComponent, meta: { title: '关于我们' } },
{ path: '/user/:id', name: 'user', component: UserComponent, meta: { title: '用户详情' } },
],
mode: 'history',
base: '/',
});
const app = createApp({
root: class Layout extends Component<object, object> {
protected initState() {
return {};
}
protected initStyles(): void {}
protected render(): VNode {
return {
tag: 'main',
children: [{ component: RouterView }],
};
}
},
});
app.use(router);
app.mount();路由配置选项
路由规则
path: URL 路径模式name: 路由名称component: 对应组件meta: 元数据
路径模式
/about: 静态路径/user/:id: 动态路径参数*: 通配符兜底
导航守卫
router.beforeEach(guard) 注册全局前置守卫:返回 false 取消导航,返回字符串重定向到该路径,返回 true 或 undefined 放行;router.afterEach(hook) 在导航提交后调用。守卫仅在编程式导航(push/replace)时执行。
router.beforeEach((to) => {
if (!isLoggedIn() && to.path !== '/login') return '/login';
return true;
});
router.afterEach((to) => {
document.title = String(to.meta?.title ?? '');
});重定向与通配路由
RouteRecord.redirect 让路由解析到目标路径(自带循环防护);path: '*' 匹配所有未命中路径,剩余路径片段可通过 params.pathMatch 读取,常用于 404 页面。
const router = createRouter({
routes: [
{ path: '/', component: HomeComponent },
{ path: '/old', redirect: '/new' },
{ path: '/new', component: NewComponent },
{ path: '*', component: NotFoundComponent },
],
});路由导航
编程式导航
router.push('/about');
router.replace('/login');
router.back();
router.forward();
router.go(-1);声明式导航
{
component: RouterLink,
props: {
to: '/user/42',
activeClass: 'is-active',
children: ['用户详情'],
},
}路由参数
获取路由参数
class UserComponent extends Component<object, { userId: string }> {
protected initState() {
return { userId: '' };
}
protected initStyles(): void {}
protected onMounted() {
const route = this.router?.getCurrentRoute();
this.state.userId = String(route?.params.id ?? '');
}
protected render(): VNode {
return {
tag: 'h1',
children: ['用户详情 '],
};
}
}路由参数变化监听
const stopListening = router.onRouteChange((to) => {
console.log('route changed to', to.path);
});
stopListening();路由元数据
const router = createRouter({
routes: [
{ path: '/', component: HomeComponent, meta: { title: '首页' } },
{ path: '/dashboard', component: DashboardComponent, meta: { title: '仪表盘' } },
],
});路由模式
History 模式
const router = createRouter({
mode: 'history',
routes: [...],
});History 模式使用 HTML5 History API,需要服务器回退到应用入口。
Hash 模式
const router = createRouter({
mode: 'hash',
routes: [...],
});Hash 模式不需要服务器改写 URL,适合静态托管场景。
嵌套路由
父组件中可以使用 RouterView 显示子路由内容。
class DashboardComponent extends Component<object, object> {
protected initState() {
return {};
}
protected initStyles(): void {}
protected render(): VNode {
return {
tag: 'div',
children: [
{ tag: 'h1', children: ['仪表盘'] },
{ component: RouterView },
],
};
}
}路由 API
路由实例方法
push(location): 导航到指定位置replace(location): 替换当前历史记录back() / forward() / go(n): 调用浏览器历史记录能力onRouteChange(callback): 监听路由变化getCurrentRoute(): 读取当前路由信息createHref(path): 生成 href
路由对象属性
currentRoute: 当前路由信息routes: 路由配置mode: 路由模式base: 基础路径
最佳实践
路由组织
- 集中管理路由配置
- 为关键页面使用命名路由
- 合理使用动态参数和 meta
性能优化
- 保持路由组件边界清晰
- 避免在 onRouteChange 中执行昂贵操作
- 必要时拆分页面级组件
常见问题
- History 模式刷新 404:需要服务器回退规则
- 路由参数变化不更新:监听路由变化并刷新数据
- 嵌套路由不显示:确认父组件中渲染了 RouterView
总结
TSone 路由系统通过 createRouter、RouterView 和 RouterLink 提供了清晰、轻量的导航能力。