视图

Nuxt 提供了多个组件层来实现应用的用户界面。

app.vue

默认情况下,Nuxt 会将此文件视为 入口点,并在应用的每个路由中渲染其内容。

app/app.vue
<template>
  <div>
    <h1>Welcome to the homepage</h1>
  </div>
</template>
如果你熟悉 Vue,可能会好奇 main.js 在哪里(通常用于创建 Vue 应用的文件)。Nuxt 会在后台处理这部分内容。

Components

大多数组件是可重用的用户界面部分,例如按钮和菜单。在 Nuxt 中,你可以在 app/components/ 目录中创建这些组件,它们会在应用中自动可用,无需显式导入。

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

Pages

页面表示每个特定路由模式的视图。app/pages/ 目录中的每个文件都对应一个不同的路由并显示其内容。

要使用页面,创建一个 app/pages/index.vue 文件并在 app/app.vue(或删除 app/app.vue 以使用默认入口)中添加 <NuxtPage /> 组件。现在你可以通过在 app/pages/ 目录中添加新文件来创建更多页面及其对应的路由。

<template>
  <div>
    <h1>Welcome to the homepage</h1>
    <AppAlert>
      This is an auto-imported component
    </AppAlert>
  </div>
</template>
Read more in 路由 部分.

Layouts

布局是页面的外壳,为多个页面提供通用的用户界面,如头部和页脚显示。布局是使用 <slot /> 组件来显示页面内容的 Vue 文件。app/layouts/default.vue 文件将作为默认布局使用。自定义布局可以在页面元数据中设置。

如果你的应用只有单个布局,我们建议使用带有 <NuxtPage />app/app.vue 来替代。
<template>
  <div>
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>

如果你想创建更多布局并了解如何在页面中使用它们,请在 Layouts 部分 查找更多信息。

高级:扩展 HTML 模板

如果你只需要修改 <head>,可以参考 SEO 与元信息 部分

你可以通过添加一个注册钩子的 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) })
})
Read more in Docs > 4 X > Guide > Going Further > Hooks.