mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
Added code examples for the router docs. (#67)
This commit is contained in:
parent
9a30804726
commit
998f508793
@ -34,9 +34,45 @@ The Router component communicates with `RouteAgent` and will automatically resol
|
||||
|
||||
First, you want to create a type that represents all the states of your application. Do note that while this typically is an enum, structs are supported as well, and that you can nest other items that implement `Switch` inside.
|
||||
|
||||
Then you should derive `Switch` for your type. For enums, every variant must be annotated with `#[to = "/some/route"]`, or if you use a struct instead, that must appear outside the struct declaration.
|
||||
Then you should derive `Switch` for your type. For enums, every variant must be annotated with `#[to = "/some/route"]`, or if you use a struct instead, that must appear outside the struct declaration.
|
||||
|
||||
Do note that the implementation generated by the derive macro for `Switch` will try to create each variant in order from first to last, so if any route could possibly match two of your specified `to` annotations, then the first one will match, and the second will never be tried.
|
||||
```rust
|
||||
#[derive(Switch)]
|
||||
enum AppRoute {
|
||||
#[to="/login"]
|
||||
Login,
|
||||
#[to="/register"]
|
||||
Register,
|
||||
#[to="/delete_account"]
|
||||
Delete,
|
||||
#[to="/posts/{id}"]
|
||||
ViewPost(i32),
|
||||
#[to="/posts/view"]
|
||||
ViewPosts,
|
||||
#[to="/"]
|
||||
Home
|
||||
}
|
||||
```
|
||||
|
||||
Do note that the implementation generated by the derive macro for `Switch` will try to match each variant in order from first to last, so if any route could possibly match two of your specified `to` annotations, then the first one will match, and the second will never be tried. For example, if you defined the following `Switch`, the only route that would be matched would be `AppRoute::Home`.
|
||||
|
||||
```rust
|
||||
#[derive(Switch)]
|
||||
enum AppRoute {
|
||||
#[to="/"]
|
||||
Home,
|
||||
#[to="/login"]
|
||||
Login,
|
||||
#[to="/register"]
|
||||
Register,
|
||||
#[to="/delete_account"]
|
||||
Delete,
|
||||
#[to="/posts/{id}"]
|
||||
ViewPost(i32),
|
||||
#[to="/posts/view"]
|
||||
ViewPosts,
|
||||
}
|
||||
```
|
||||
|
||||
You can also capture sections using variations of `{}` within your `#[to = ""]` annotation. `{}` means capture text until the next separator \(either "/", "?", "&", or "\#" depending on the context\). `{*}` means capture text until the following characters match, or if no characters are present, it will match anything. `{<number>}` means capture text until the specified number of separators are encountered \(example: `{2}` will capture until two separators are encountered\).
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user