Blazor_WASM之4:路由

Blazor_WASM之4:路由

Blazor_WASM之4:路由

路由模板

通过 Router组件可在 Blazor 应用中路由到 Razor 组件。 Router 组件在 Blazor 应用的 App 组件中使用。App组件模板如下

1
2
3
4
5
6
7
8
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<p>Sorry, there's nothing at this address.</p>
</NotFound>
</Router>

在运行时,RouteView组件有两个作用:

  • 从 Router 接收 RouteData(例如/test)以及所有路由参数。
  • 使用指定的组件的布局来呈现该组件,包括任何后续嵌套布局。

组件支持使用多个 @page 指令,/blazor-route和/different-blazor-route都能跳转到该界面

1
2
3
4
@page "/blazor-route"
@page "/different-blazor-route"

<h1>Blazor routing</h1>

也可以将@page替换成@attribute

1
2
@page "/test"
@attribute [Route("test")]

重要:想要正确解析URL,必须在<head>中包含<base>,也就是在wwwroot中的index.html中<head>中包含<base>

1
2
3
4
5
<head>
...
<base href="/" />
...
</head>

元素聚焦

切换到指定页面后,可以将UI焦点设置到指定元素。

<FocusOnNavigate RouteData="@routeData" Selector="h1" />

当 Router 组件导航到新页面时,FocusOnNavigate组件将焦点设置到页面的顶层标题 (<h1>)。

NotFound

如果找不到所请求路由的内容,则 Router组件允许应用指定自定义内容

1
2
3
4
<NotFound>
<h1>Sorry</h1>
<p>Sorry, there's nothing at this address.</p>
</NotFound>

路由参数

路由器使用相同的路由参数名称来填充组件参数,且路由参数不区分大小写。

1
2
3
4
5
6
7
8
9
10
@page "/test/{name}"

<h3>Test</h3>

<p>传入的参数是:@Name</p>

@code {
[Parameter]
public string? Name{ set;get; }
}

在地址栏中填写/test/哈哈哈

但是,如果地址栏只写/test,也就是不写参数,则会出现

改写为@page "/test/{name?}",name则变成可选参数,地址栏仍然只写/test,则会出现

路由约束

路由约束强制在路由段和组件之间进行类型匹配,例如只允许id为int类型

1
2
3
4
5
6
7
8
@page "/user/{Id:int}"

<h1>User Id: @Id</h1>

@code {
[Parameter]
public int Id { get; set; }
}

路由约束类型

路由约束也可以使用可选参数,比如下面的Id是必须,option是可选

@page "/user/{Id:int}/{Option:bool?}"

CatchAll路由参数

如果想把/test/a/b/c/test/后面的内容全部当做参数,则可以使用/test/{*par}来进行提取。

1
2
3
4
5
6
@page "/catch-all/{*pageRoute}"

@code {
[Parameter]
public string? PageRoute { get; set; }
}

查询字符串

查询字符串的样式如/test?name=tom&age=18后面的内容就是查询字符串,查询字符串支持的类型有bool, DateTime, decimal, double, float, Guid, int, long, string。使用方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@page "/test"

<h3>Test</h3>

<p>姓名:@Name</p>
<p>年龄:@Age</p>
<p>性别:@(MyProperty)</p>

@code {

[Parameter]
[SupplyParameterFromQuery]
public string? Name{ set;get; }

[Parameter]
[SupplyParameterFromQuery]
public int? Age { set; get; }

[Parameter]
[SupplyParameterFromQuery]
public bool Gender { set; get; }

public string MyProperty
{
get { return Gender?"男":"女"; }
}
}

在地址栏输入.../test?name=Tom&age=18&gender=true

SupplyParameterFromQuery的Name属性可以指定查询参数的名字,下面是一个将查询参数放到同一个数组的案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@page "/test"

<h3>Test</h3>
@foreach (var item in stars)
{
<p>@item</p>
}

@code {

[Parameter]
[SupplyParameterFromQuery(Name ="star")]
public string[]? stars { set; get; }

}

在地址栏输入.../test?star=a&star=b&star=c

作者

步步为营

发布于

2024-05-08

更新于

2025-03-15

许可协议