0
0
Vueframework~5 mins

Defining routes in Vue

Choose your learning style9 modes available
Introduction

Routes help your app show different pages when users click links or enter URLs. They make your app feel like a website with many pages.

You want to show a homepage and an about page in your app.
You need to let users visit different sections like profile, settings, or dashboard.
You want to change the displayed content without reloading the whole page.
You want to handle URLs so users can bookmark or share specific pages.
You want to show a 'not found' page when users enter a wrong URL.
Syntax
Vue
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

The routes array lists all pages with their URL paths and components.

createRouter sets up the router with history mode and routes.

Examples
Defines two routes: homepage and contact page.
Vue
const routes = [
  { path: '/', component: Home },
  { path: '/contact', component: Contact }
]
Route with a dynamic segment :id to show different user profiles.
Vue
const routes = [
  { path: '/user/:id', component: UserProfile }
]
Catch-all route to show a 'not found' page for unknown URLs.
Vue
const routes = [
  { path: '/:pathMatch(.*)*', component: NotFound }
]
Sample Program

This Vue app shows a home page at '/' and an about page at '/about'. The router changes the displayed page without reloading.

Vue
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'

const Home = { template: '<h1>Home Page</h1>' }
const About = { template: '<h1>About Page</h1>' }

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const app = createApp({})
app.use(router)
app.mount('#app')
OutputSuccess
Important Notes

Always import and use the router in your main Vue app to enable routing.

Use router-link components to create accessible links between routes.

Test routes in the browser by typing URLs or clicking links to see pages change.

Summary

Routes connect URLs to components to show different pages.

Define routes in an array with path and component.

Use createRouter and createWebHistory to set up routing.