在 Blazor 应用中,我们可以通过使用 @page 指令将组件路由到特定的 URL。在某些情况下,我们可能需要在路由 URL 中使用变量。这时,我们可以使用花括号来包含变量名称,并在组件中使用 [Parameter] 属性来接收这些变量。以下是一个示例:
@page "/blog/{postId:int}"
@inherits PostDetailsBase
@Post.Title
@Post.Body
@code {
[Parameter]
public int PostId { get; set; }
private Post Post { get; set; }
protected override void OnParametersSet()
{
Post = DataService.GetPostById(PostId);
}
}
在上面的示例中,@page 指令用于将组件路由到 /blog/{postId:int} 这个 URL。{postId:int} 表示变量名称为 postId,类型为整数。组件使用 [Parameter] 属性来接收这个变量,并使用 DataService 在 OnParametersSet 方法中获取相应的博客文章。