透過 100 多個技巧的集合來學習 Nuxt!

檢視

Nuxt 提供多個元件層來實作您的應用程式的使用者介面。

app.vue

The app.vue file is the entry point of your application

預設情況下,Nuxt 會將此檔案視為進入點,並為應用程式的每個路由渲染其內容。

app.vue
<template>
  <div>
   <h1>Welcome to the homepage</h1>
  </div>
</template>
如果您熟悉 Vue,您可能會想知道 main.js(通常建立 Vue 應用程式的檔案)在哪裡。 Nuxt 在幕後執行此操作。

元件

Components are reusable pieces of UI

大多數元件都是可重複使用的使用者介面部分,例如按鈕和選單。在 Nuxt 中,您可以在 components/ 目錄中建立這些元件,它們將自動在您的應用程式中可用,而無需明確匯入它們。

<template>
  <div>
    <h1>Welcome to the homepage</h1>
    <AppAlert>
      This is an auto-imported component.
    </AppAlert>
  </div>
</template>

頁面

Pages are views tied to a specific route

頁面代表每個特定路由模式的視圖。 pages/ 目錄中的每個檔案都代表不同的路由,顯示其內容。

若要使用頁面,請建立 pages/index.vue 檔案,並將 <NuxtPage /> 元件新增至 app.vue (或移除 app.vue 以使用預設入口)。現在您可以在 pages/ 目錄中新增更多檔案,建立更多頁面及其對應的路由。

<template>
  <div>
    <h1>Welcome to the homepage</h1>
    <AppAlert>
      This is an auto-imported component
    </AppAlert>
  </div>
</template>
請參閱路由章節以瞭解更多資訊。

版面配置

Layouts are wrapper around pages

版面配置是頁面的包裝器,包含多個頁面通用的使用者介面,例如頁首和頁尾顯示。版面配置是使用 <slot /> 元件來顯示**頁面**內容的 Vue 檔案。layouts/default.vue 檔案將預設使用。自訂版面配置可以設定為頁面中繼資料的一部分。

如果您的應用程式只有一個版面配置,我們建議您改用包含 <NuxtPage />app.vue
<template>
  <div>
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>

如果您想建立更多版面配置並了解如何在頁面中使用它們,請在版面配置章節中找到更多資訊。

進階:擴展 HTML 模板

如果您只需要修改 <head>,可以參考SEO 和 meta 章節

您可以透過新增註冊鉤子的 Nitro 外掛程式來完全控制 HTML 模板。render:html 鉤子的回呼函式可讓您在 HTML 傳送到用戶端之前修改它。

server/plugins/extend-html.ts
export default 
defineNitroPlugin
((
nitroApp
) => {
nitroApp
.
hooks
.
hook
('render:html', (
html
, {
event
}) => {
// This will be an object representation of the html template.
console
.
log
(
html
)
html
.
head
.
push
(`<meta name="description" content="My custom description" />`)
}) // You can also intercept the response here.
nitroApp
.
hooks
.
hook
('render:response', (
response
, {
event
}) => {
console
.
log
(
response
) })
})
請參閱文件 > 指南 > 進階 > 鉤子以瞭解更多資訊。