Nuxt4 页面与组件
Nuxt 里代码放在哪
前面讲了路由、布局、自动导入,但还没说”页面和组件到底怎么写”。这一篇补上这个缺口,让你能真正动手写出可运行的界面。
Nuxt 约定了三个最关键的位置:
app.vue:整个应用的根组件,所有页面都挂在它下面。app/pages/:放页面组件,文件名直接决定路由地址。app/components/:放可复用的组件,写进components/后无需import就能在模板里使用。
目录结构在 Nuxt4 目录结构 一篇里有完整说明,这里先专注”怎么写”。
根组件 app.vue
新建项目时 app/app.vue 通常长这样:
<template>
<div>
<h1>你好,Nuxt</h1>
<NuxtPage />
</div>
</template>
<NuxtPage /> 是占位符,表示”这里渲染当前路由对应的页面”。只要你在 app/pages/ 下建了页面,Nuxt 就会自动把对应页面替换到这里。
写一个页面
在 app/pages/ 下新建 index.vue,它就是网站首页(/):
<template>
<section>
<h2>文章列表</h2>
<p>这是首页内容。</p>
<NuxtLink to="/about">去关于页</NuxtLink>
</section>
</template>
<script setup>
// 页面里的逻辑写在这里
const title = '文章列表'
</script>
再新建 app/pages/about.vue,访问 /about 就能看到它:
<template>
<p>这是关于页面。</p>
<NuxtLink to="/">返回首页</NuxtLink>
</template>
页面之间的跳转要用 <NuxtLink>,不要用普通的 <a href>。NuxtLink 做的是客户端路由切换,不会整页刷新,体验更流畅。
写一个组件并自动导入
在 app/components/ 下新建 UserCard.vue:
<template>
<div class="card">
<h3>{{ name }}</h3>
<slot />
</div>
</template>
<script setup>
defineProps({
name: String
})
</script>
回到页面里,直接把 <UserCard /> 当标签用,不用写 import:
<template>
<UserCard name="小明">
这是卡片里的正文内容。
</UserCard>
</template>
这就是 Nuxt4 自动导入机制 提到的”组件免导入”:文件名就是组件名,components/ 下的 UserCard.vue 对应标签 <UserCard />。子目录也能用,例如 components/foo/Bar.vue 对应 <FooBar />。
在页面里管理数据
页面和组件都是标准的 Vue 单文件组件,响应式写法完全一致:
<template>
<p>计数:{{ count }}</p>
<button @click="count++">加一</button>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
ref、reactive 这些来自 Vue 的 API,Nuxt 也做了自动导入,上面这行 import 甚至可以省略。
小结
到这里,你已经能独立完成一个 Nuxt 页面了:
app.vue放全局根结构,用<NuxtPage />承载页面。app/pages/下建文件即生成路由,用<NuxtLink>跳转。app/components/下放组件,写进模板即用,无需import。- 页面与组件里的逻辑、响应式数据,和 Vue 写法完全一致。
接下来在 Nuxt4 静态资源 一篇,我们看看图片、样式等资源怎么放、怎么引用。