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

Routes Setup करना

Routes एक list हैं जो हर URL path को उस component से map करती हैं जो दिखाया जाना चाहिए।

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

हर route object का एक path और एक component है, और optionally एक name और meta। createRouter में array register करें। Names links को path changes के against robust बनाते हैं, और एक regex param वाला catch-all route not-found pages handle करता है।

Note: routes को names दें ताकि आप path की बजाय name से link कर सकें।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. leading slash भूल जाना
  2. catch-all route पहले रखना
  3. paths duplicate करना
चैप्टर सारांश
  • routes paths को components से map करते हैं
  • name और meta optional हैं
  • Catch-all 404 handle करता है
  • Overlapping paths के लिए order matter करता है
🔒

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.