簡體   English   中英

將組件中的一些元素放入 head 標簽中

[英]Put some elements from component into head tag

我想要從 component 到 go 到head標簽的一些標簽。 我想放入名為headslot中。 怎么能做到這一點?

布局.astro

<html>
    <head>
        <slot name="head" />
    </head>
    <body>
        <slot />
        <mycomponent />
    </body>
</html>

我的組件.astro

<link .... slot="head">
<div>
    ...
</div> 

解決方案

可以放置一個標簽,但只能從你調用放置單個<head>的布局的地方使用像這樣的slots

在 Layout.astro 中創建一個

  • 默認插槽和
  • 命名插槽,例如name="head"但你可以使用任何名稱

    <head>
        <title>{title}</title>
        <slot name="head"/>
    </head>
    
    <body>
        <slot />
    </body>

然后在您的頁面或調用布局的組件中


<Layout title="Welcome to Astro.">
    <link slot="head" rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <main>
        <h1>Astro</h1>
    </main>
</Layout>

說明

  • 插槽概念獨立於布局和頭部
  • Layout 組件可以有任何名稱,並且可以在任何組件中使用
  • 在 Astro 中,每頁只能有一個<head>元素,所有其他使用的<head>標簽將保留在原處,不會被編譯器移動到主頂部<head>
  • 頁面及其所有子組件都可以使用插槽概念通過插槽在單父<head>標簽內填充 it 標簽
  • 這僅在組件直接包含組件時才有效,例如提供插槽的布局

參考

注意:下面來自 Astro 文檔網站的參考建議“將單個<head>及其內容放在布局組件中。”

https://docs.astro.build/en/guides/troubleshooting/#using-head-in-a-component

命名插槽: https://docs.astro.build/en/core-concepts/astro-components/#named-slots

暫無
暫無

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

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