Blazor_WASM之4:路由

Blazor_WASM之4:路由

路由模板

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

<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都能跳转到该界面

@page "/blazor-route"
@page "/different-blazor-route"

<h1>Blazor routingh1>

也可以将@page替换成@attribute

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

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

<head>
    ...
    <base href="/" />
    ...
head>

元素聚焦

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

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

)。

NotFound

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

<NotFound>
     <h1>Sorryh1>
     <p>Sorry, there's nothing at this address.p>
NotFound>

路由参数

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

@page "/test/{name}"

<h3>Testh3>

<p>传入的参数是:@Namep>

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

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

Blazor_WASM之4:路由_第1张图片

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

Blazor_WASM之4:路由_第2张图片

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

Blazor_WASM之4:路由_第3张图片

路由约束

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

@page "/user/{Id:int}"

<h1>User Id: @Idh1>

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

路由约束类型

Blazor_WASM之4:路由_第4张图片

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

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

CatchAll路由参数

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

@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。使用方法如下:

@page "/test"

<h3>Testh3>

<p>姓名:@Namep>
<p>年龄:@Agep>
<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

Blazor_WASM之4:路由_第5张图片

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

@page "/test"

<h3>Testh3>
@foreach (var item in stars)
{
    <p>@itemp>
}

@code {

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

}

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

Blazor_WASM之4:路由_第6张图片

你可能感兴趣的:(Blazor,WASM,wasm,c#,.net,asp.net,前端)