Skip to content

Commit e9aca9e

Browse files
authored
docs(zh/typed-routes): Sync translation of typed-routes page. (#2564)
The current Chinese version of typed-routes is somewhat outdated. This commit synchronizes the translation of this file with the latest content from the English version.
1 parent bb3b721 commit e9aca9e

File tree

1 file changed

+71
-5
lines changed

1 file changed

+71
-5
lines changed
Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,77 @@
1-
# 类型化路由 (v4.1.0+)
1+
# 类型化路由 <Badge type="tip" text="v4.4.0+" />
22

33
<RuleKitLink />
44

5-
::: danger ‼️ 实验性功能
5+
![RouterLink to autocomplete](https://user-images.githubusercontent.com/664177/176442066-c4e7fa31-4f06-4690-a49f-ed0fd880dfca.png)
66

7-
从 v4.1.0 开始,我们引入一个新的功能,称为类型化路由。这个**实验性**功能通过 Vite/webpack/Rollup 插件启用
7+
可以为路由配置一个类型化的映射表。 虽然可以手动实现,但更推荐使用 [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) 插件来自动生成路由及其类型
88

9-
![RouterLink to autocomplete](https://user-images.githubusercontent.com/664177/176442066-c4e7fa31-4f06-4690-a49f-ed0fd880dfca.png)
9+
## 手动配置
10+
11+
以下是一个手动配置类型化路由的示例:
12+
13+
```ts
14+
// 要为你的路由添加类型,需要从 vue-router 导入 `RouteRecordInfo` 类型
15+
import type { RouteRecordInfo } from 'vue-router'
16+
17+
// 定义一个路由的 interface
18+
export interface RouteNamedMap {
19+
// 每一个键都是一个名称
20+
home: RouteRecordInfo<
21+
// 这里我们的名称是相同的
22+
'home',
23+
// 这是路径,它会出现在自动补全中
24+
'/',
25+
// 这些是原始参数(可以传递给 router.push() 和 RouterLink 的 "to" 属性)
26+
// 在这种情况下,不允许有任何参数
27+
Record<never, never>,
28+
// 这些是标准化后的参数(即通过 `useRoute()` 获取到的参数)
29+
Record<never, never>,
30+
// 这是一个所有子路由名称的联合类型,而在本例中,没有子路由
31+
never
32+
>
33+
// 对每一条路由都要重复这个步骤……
34+
// 注意,你可以随意为它们命名
35+
'named-param': RouteRecordInfo<
36+
'named-param',
37+
'/:name',
38+
{ name: string | number }, // 允许是字符串或数字
39+
{ name: string }, // 但从 URL 获取时始终为字符串
40+
'named-param-edit'
41+
>
42+
'named-param-edit': RouteRecordInfo<
43+
'named-param-edit',
44+
'/:name/edit',
45+
{ name: string | number }, // 我们还需要包含父级路由的参数
46+
{ name: string },
47+
never
48+
>
49+
'article-details': RouteRecordInfo<
50+
'article-details',
51+
'/articles/:id+',
52+
{ id: Array<number | string> },
53+
{ id: string[] },
54+
never
55+
>
56+
'not-found': RouteRecordInfo<
57+
'not-found',
58+
'/:path(.*)',
59+
{ path: string },
60+
{ path: string },
61+
never
62+
>
63+
}
64+
65+
// 最后,你需要把这份路由映射表扩展到 Vue Router 的类型定义中
66+
declare module 'vue-router' {
67+
interface TypesConfig {
68+
RouteNamedMap: RouteNamedMap
69+
}
70+
}
71+
```
72+
73+
::: tip
74+
75+
这种方式确实繁琐且容易出错。正因如此,强烈推荐使用 [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) 来自动生成路由和类型。
1076

11-
[查看 v4.1 版本的发布说明](https://github.com/vuejs/router/releases/tag/v4.1.0) 获取有关此功能的更多信息。[查看插件](https://github.com/posva/unplugin-vue-router) 的 GitHub 仓库获取安装说明和文档。
77+
:::

0 commit comments

Comments
 (0)