0
0
Vueframework~5 mins

Pages and file-based routing in Vue

Choose your learning style9 modes available
Introduction

Pages and file-based routing help you create website pages easily by just adding files. The file names decide the web address automatically.

When building a website with multiple pages like home, about, and contact.
When you want to add new pages quickly without writing routing code.
When you want your URLs to match your file names for easy navigation.
When you want to organize your project by folders and files that reflect the site structure.
Syntax
Vue
<project-root>/pages/<page-name>.vue

// Example: pages/about.vue

<template>
  <h1>About Page</h1>
</template>

<script setup>
// Vue component code here
</script>
Each .vue file inside the pages folder automatically becomes a route.
Folders inside pages create nested routes matching the folder structure.
Examples
This file creates the home page at URL /.
Vue
pages/index.vue

<template>
  <h1>Home Page</h1>
</template>
This file creates the about page at URL /about.
Vue
pages/about.vue

<template>
  <h1>About Us</h1>
</template>
This file creates a blog list page at URL /blog.
Vue
pages/blog/index.vue

<template>
  <h1>Blog List</h1>
</template>
This file creates a dynamic route for blog posts like /blog/123, where 123 is the post ID.
Vue
pages/blog/[id].vue

<template>
  <h1>Blog Post</h1>
  <p>Post ID: {{ id }}</p>
</template>

<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const id = route.params.id
</script>
Sample Program

This example shows three pages: home, about, and contact. Each page is a separate file inside the pages folder. The URLs will be /, /about, and /contact automatically.

Vue
<!-- File: pages/index.vue -->
<template>
  <h1>Welcome to Home</h1>
  <nav>
    <a href="/about">About</a> |
    <a href="/contact">Contact</a>
  </nav>
</template>

<!-- File: pages/about.vue -->
<template>
  <h1>About Us</h1>
  <p>This is the about page.</p>
</template>

<!-- File: pages/contact.vue -->
<template>
  <h1>Contact</h1>
  <p>Contact us at contact@example.com</p>
</template>
OutputSuccess
Important Notes

File names like index.vue become the root of their folder route.

Dynamic routes use square brackets, like [id].vue, to capture URL parts.

Use vue-router hooks like useRoute() to access route parameters inside components.

Summary

File names in the pages folder create routes automatically.

Folders create nested routes matching the URL path.

Dynamic routes use square brackets to capture variables from the URL.