Routes setup
Routes are a list that maps each URL path to the component that should be shown.
In this page:
Syntax
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/path', component: ComponentName, name: 'route-name' }
];
const router = createRouter({ history: createWebHistory(), routes });
app.use(router);
Routes setup
Each route object has a path and a component, and optionally a name and meta. Register the array in createRouter. Names make links robust to path changes, and a catch-all route with a regex param handles not-found pages.
Note:
Give routes names so you can link by name instead of path.
Example: Routes setup
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const Home = { template: "<h2>Home page</h2>" };
const About = { template: "<h2>About page</h2>" };
const NotFound = { template: "<h2>404 - not found</h2>" };
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ path: "/", name: "home", component: Home },
{ path: "/about", name: "about", component: About },
{ path: "/:pathMatch(.*)*", component: NotFound },
],
});
Vue.createApp({}).use(router).mount("#app");
router.isReady().then(() => {
console.log("route names:", router.getRoutes().map((r) => r.name).filter(Boolean));
console.log("current:", document.querySelector("h2").textContent);
});
</script>
</body>
</html>
<!-- Output:
Rendered: Home page
console: route names: home,about
console: current: Home page
-->
Live Example
Related Topics
Common Mistakes
- Forgetting the leading slash
- Placing the catch-all route first
- Duplicating paths
Chapter Summary
- routes map paths to components
- name and meta are optional
- Catch-all handles 404
- Order matters for overlapping paths
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: