← Back to Vue.js Course | Chapter 7: Vue Router | Lesson 2 of 7

Routes setup

Routes are a list that maps each URL path to the component that should be shown.

In this page:

  1. Routes setup
Syntax
markup
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

markup
<!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
  1. Forgetting the leading slash
  2. Placing the catch-all route first
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.