Pages and file-based routing
In Nuxt you do not describe routes by hand: every .vue file in the app/pages/ folder becomes a page by itself, and the file path sets its address. This approach is called file-based routing.
File and address
| File | Address |
|---|---|
app/pages/index.vue | / |
app/pages/about.vue | /about |
app/pages/posts/index.vue | /posts |
app/pages/posts/new.vue | /posts/new |
An index.vue file handles the address of its folder; other files add their name to the address.
A new page
Create an "About" page:
npx nuxi add page aboutThe command creates app/pages/about.vue. Replace its content:
<!-- app/pages/about.vue -->
<template>
<section>
<h2>About the blog</h2>
<p>Anna and Oleg write about web development here.</p>
</section>
</template>Open http://localhost:3000/about and the "About the blog" section appears. No restart is needed: Nuxt notices new files itself.
A page in a folder
The list of posts will live at /posts. Create app/pages/posts/index.vue (or run npx nuxi add page posts/index):
<!-- app/pages/posts/index.vue -->
<script setup lang="ts">
const posts = [
{ id: 1, title: 'First post', text: 'Hello, world!' },
{ id: 2, title: 'Learning Nuxt', text: 'Pages from files.' }
]
</script>
<template>
<section>
<h2>Posts</h2>
<article v-for="post in posts" :key="post.id">
<h3>{{ post.title }}</h3>
<p>{{ post.text }}</p>
</article>
</section>
</template>Two posts appear at /posts. For now they are written right in the file; later the list will come from the server.
An address that does not exist
If you open an address with no matching file, for example /contacts, Nuxt shows a 404 error page. Later you will replace it with your own.
How it works
Under the hood Nuxt uses the same Vue Router as a plain Vue app. The only difference is that Nuxt builds the list of routes from files itself. All routes of the project are visible in Nuxt DevTools on the Pages tab.
Common mistake
A page must have a single root element. If the <template> holds, say, an <h2> and a <p> side by side with no common wrapper, Nuxt prints a warning in the console and page transitions may misbehave. Wrap the page content in one element: <section>, <div> or <main>.