由於 Inertia 驅動的 JavaScript 應用程式是在文件 <body>
內渲染的,因此它們無法將標記渲染到文件 <head>
,因為它超出它們的作用域。為了幫助解決這個問題,Inertia 提供了一個 <Head>
組件,可用於設定頁面 <title>
、<meta>
標籤,以及其他 <head>
元素。
<Head>
組件只會取代不在您伺服器端根範本中的 <head>
元素。<Head>
組件在 Svelte 介面卡中不可用,因為 Svelte 已經提供自己的 <svelte:head>
組件。若要將 <head>
元素新增到您的頁面,請使用 <Head>
組件。在此組件中,您可以包含您想要新增至文件 <head>
的元素。
import { Head } from '@inertiajs/vue3'
<Head>
<title>Your page title</title>
<meta name="description" content="Your page description">
</Head>
如果您只需要將 <title>
新增到文件 <head>
,您可以簡單地將標題作為屬性傳遞給 <Head>
組件。
import { Head } from '@inertiajs/vue3'
<Head title="Your page title" />
您可以使用 createInertiaApp
設定方法中的 title
回呼,全域修改頁面 <title>
。 通常,這個方法會在您的應用程式的主要 JavaScript 檔案中被呼叫。標題回呼的一個常見用途是在每個頁面標題之前或之後自動新增應用程式名稱。
createInertiaApp({
title: title => `${title} - My App`,
// ...
})
定義 title
回呼之後,當您使用 <Head>
組件設定標題時,會自動呼叫回呼。
import { Head } from '@inertiajs/vue3'
<Head title="Home">
在此範例中,將會產生下列 <title>
標籤。
<title>Home - My App</title>
當您在 <Head>
組件中使用 <title>
標籤設定標題時,也會呼叫 title
回呼。
import { Head } from '@inertiajs/vue3'
<Head>
<title>Home</title>
</Head>
在整個應用程式中,可以有多個 <Head>
組件的實例。例如,您的版面配置可以設定一些預設的 <Head>
元素,然後您個別的頁面可以覆寫這些預設值。
// Layout.vue
import { Head } from '@inertiajs/vue3'
<Head>
<title>My app</title>
<meta head-key="description" name="description" content="This is the default description" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
</Head>
// About.vue
import { Head } from '@inertiajs/vue3'
<Head>
<title>About - My app</title>
<meta head-key="description" name="description" content="This is a page specific description" />
</Head>
Inertia 只會渲染一個 <title>
標籤;然而,所有其他標籤都會堆疊,因為它們有多個實例是有效的。為了避免您的 <head>
中出現重複標籤,您可以使用 head-key
屬性,這會確保標籤只會渲染一次。在上面的範例中,<meta name="description">
標籤說明了這一點。
上面的程式碼範例會渲染下列 HTML。
<head>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>About - My app</title>
<meta name="description" content="This is a page specific description" />
</head>
在建置實際應用程式時,建立一個自訂的 head 組件來擴充 Inertia 的 <Head>
組件有時會很有幫助。這可以讓您有一個地方設定應用程式範圍的預設值,例如將應用程式名稱附加到頁面標題。
<!-- AppHead.vue -->
<script setup>
import { Head } from '@inertiajs/vue3'
defineProps({ title: String })
</script>
<template>
<Head :title="title ? `${title} - My App` : 'My App'">
<slot />
</Head>
</template>
建立自訂組件後,您可以簡單地開始在您的頁面中使用自訂組件。
import AppHead from './AppHead'
<AppHead title="About" />