首页 > 解决方案 > 如何在 blazor 中设置页面标题?

问题描述

由于 Blazor 是一个 SPA 框架,我想知道是否可以为 Blazor 中的每个单独页面设置页面标题?

我目前正在开发 Blazor webassembly 项目,但无法弄清楚如何添加页面标题,因为只有一个 index.html 应该在 SPA 中,但如果可以实现为每个设置标题,那将非常有用“页”。

标签: blazor

解决方案


注意:从 .Net 6.0 开始,官方支持更改标题,因此不再需要以下解决方案。

  1. 在您的 index.html(或包含的 .js 文件)中提供以下脚本:

    <script>
         setTitle = (title) => { document.title = title; };
    </script>
    
  1. 在每个页面中注入 jsinterop:

    @inject IJSRuntime JSRuntime;
    
  2. 每次渲染后,将文档标题设置为您选择的值:

    @code
    {
       protected override async Task OnAfterRenderAsync(bool firstRender)
       {
          await JSRuntime.InvokeVoidAsync("setTitle", "this is the new title"); ;        
       }    
    }
    

推荐阅读