透過 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 章節

您可以透過新增註冊 Hook 的 Nitro 外掛程式來完全控制 HTML 模板。render:html Hook 的回呼函式可讓您在將 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
) })
})
文件 > 指南 > 深入了解 > Hooks中閱讀更多內容。