第三章 组件(8)- 控制 <head> 内容

Razor 组件可以修改页面的 HTML <head> 元素内容,包括页标题<title>元素、元数据<meta>元素、<base><link>等。

HeadOutlet组件

在Blazor中,可以通过HeadOutlet组件来控制HTML中的 <head> 内容。

HeadOutlet组件用于<head>元素内,用来渲染子组件中,PageTitleHeadContent组件提供的内容。

例如在BlazorServer项目模板的App.razor中,可以看到如下代码:

csharp 复制代码
......
<head>
    ......
    <HeadOutlet />
</head>
......

Blazor WebAssembly中的HeadOutlet

在客户端的项目(Blazor WebAssembly)应用中,HeadOutlet组件在 Program 文件中被添加到客户端。

csharp 复制代码
builder.RootComponents.Add<HeadOutlet>("head::after");

指定 ::after 伪选择器后,根组件的内容将追加到现有标头内容,而不是替换内容。 这使客户端项目可以在 wwwroot/index.html 中保留静态标头内容,而无需重复应用的 Razor 组件中的内容。

PageTitle和HeadContent组件

如果想要设置<title>元素,可以将<title>的内容,放置在Razor的 PageTitle 组件内,这样可以将其作为 HTML <title> 元素传递给 HeadOutlet 组件进行渲染。

如果想要设置<head>元素中除了<title>外的其他元素,可以将其放置在Razor的HeadContent组件中,其会将元素传递给HeadOutlet 组件进行渲染。

  • ControlHeadContent.razor

    csharp 复制代码
    @page "/control-head-content"
    
    <PageTitle>@title</PageTitle>
    
    <h1>Control <head> Content Example</h1>
    
    <p>
        Title: @title
    </p>
    
    <p>
        Description: @description
    </p>
    
    <HeadContent>
        <meta name="description" content="@description">
    </HeadContent>
    
    @code {
        private string description = "This description is set by the component.";
        private string title = "Control <head> Content";
    }

默认标题和布局标题

可以在App.razor或布局组件中使用PageTitle组件,如果同时在App.razor、布局组件和组件内部使用了PageTitle组件,那么其优先级为组件标题>布局标题>默认标题。

  • App.razor

    csharp 复制代码
    ......
    
    <head>
        ......
        <HeadOutlet/>
        <PageTitle>Page Title</PageTitle>
    </head>
    
    ......
相关推荐
程序员爱钓鱼21 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
PineappleCoder21 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
JIngJaneIL21 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码1 天前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_1 天前
列表渲染(v-for)
前端·javascript·vue.js
专注VB编程开发20年1 天前
C#全面超越JAVA,主要还是跨平台用的人少
java·c#·.net·跨平台
JustHappy1 天前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌1 天前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
sg_knight1 天前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm