Routing helps single-page apps (SPAs) show different pages without reloading the whole site. It makes the app feel fast and smooth, like a real website with many pages.
0
0
Why routing is needed for SPAs in Vue
Introduction
When you want users to visit different views or pages inside your SPA.
When you want to change the URL so users can bookmark or share specific parts of your app.
When you want to keep the app fast by loading only the needed parts instead of the whole page again.
When you want to handle navigation buttons like back and forward in the browser.
When you want to show different content based on user actions without refreshing the page.
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;
Routes connect URLs to components that show the right content.
createWebHistory() uses normal URLs without hashes (#).
Examples
Basic routes for home and profile pages.
Vue
const routes = [ { path: '/', component: Home }, { path: '/profile', component: Profile } ];
Route with a dynamic segment to show user details by ID.
Vue
const routes = [ { path: '/user/:id', component: User } ];
Route with extra info (meta) to protect the settings page.
Vue
const routes = [ { path: '/settings', component: Settings, meta: { requiresAuth: true } } ];
Sample Program
This Vue app uses routing to switch between Home and About pages without reloading. The links update the URL and the displayed content changes smoothly.
Vue
import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; const Home = { template: '<h2>Home Page</h2>' }; const About = { template: '<h2>About Page</h2>' }; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp({ template: ` <div> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> <router-view></router-view> </div> ` }); app.use(router); app.mount('#app');
OutputSuccess
Important Notes
Routing keeps the app fast by avoiding full page reloads.
URLs change so users can bookmark or share specific views.
Vue Router is the official routing library for Vue apps.
Summary
Routing lets SPAs show different pages without reloading.
It changes the URL so users can share or bookmark views.
Vue Router connects URLs to components to display the right content.