簡體   English   中英

Blazor WebAssembly 更新頁面標題

[英]Blazor WebAssembly Update Page Title

框架:.NET Core 3.1(Blazor WebAssembly)

我剛剛搭建了一個簡單的 Blazor WebAssembly 應用程序,並添加了多個頁面。 在重定向到特定頁面時,我想將窗口/選項卡標題更新為[Page Name] | My App [Page Name] | My App

在 ASP.NET MVC 或 Core 中,我們可以使用ViewBag來更新Layout.cshtml中的<title>元素。

Blazor WebAssembly 應用程序中的等效方法是什么?

謝謝。

You should be using the Microsoft.AspNetCore.Components.Web.Extensions nuget package: https://www.nuget.org/packages/Microsoft.AspNetCore.Components.Web.Extensions . 它目前仍處於預發布狀態,但穩定。

完全符合您的要求,您可以獲得<Title><Link><Meta>標記的組件。 它仍然使用 JavaScript 來執行更新,但它比其他解決方案干凈得多。 我個人在生產應用程序中成功使用了這個 package。 以下是如何設置它:

  1. 安裝 nuget package Install-Package Microsoft.AspNetCore.Components.Web.Extensions -Prerelease
  2. wwww根文件夾下的index.html文件中,添加對 JS 文件的引用: <script src="_content/Microsoft.AspNetCore.Components.Web.Extensions/headManager.js" type="module"></script>
  3. On any *.razor page you want to set the title on, or in the _Imports.razor file for a folder, add the using directive: @using Microsoft.AspNetCore.Components.Web.Extensions.Head
  4. 根據需要使用各種標簽:
<Title value="My Page Title" />
<Meta name="description" content="My Blazor Component" />
<Link rel="icon" type="image/x-icon" href="/favicon.ico" />
<Link rel="alternate" href="/feed.rss" type="application/rss+xml" />

同樣,這里有一篇關於如何設置頁面標題的不同博客文章。 本質上,您使用導航管理器注入當前頁面,然后使用 JS Interop 調用更新頁面標題。

https://www.iambacon.co.uk/blog/setting-the-document-title-in-your-blazor-app

肯定有幾種方法可以做到這一點。 如果您在實施時遇到問題,請告訴我!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM