Vue.js Lesson 9: Vue Router

💚 Vue.js CourseLesson 9 of 10 · 90% complete

Vue Router is the official routing library for Vue. It comes pre-configured when you select “Router” during project setup.

Router Setup

// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "@/views/HomeView.vue";

const routes = [
  { path: "/", component: HomeView },
  { path: "/about", component: () => import("@/views/AboutView.vue") },
  { path: "/blog/:id", component: () => import("@/views/BlogPost.vue") },
  { path: "/:pathMatch(.*)*", component: () => import("@/views/NotFound.vue") }
];

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

export default router;

RouterLink & Navigation

<template>
  <!-- RouterLink instead of a tag -->
  <RouterLink to="/">Home</RouterLink>
  <RouterLink to="/about" active-class="active">About</RouterLink>
  <RouterLink :to="{ name: 'blog', params: { id: post.id } }">Blog Post</RouterLink>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

console.log(route.params.id);   // dynamic param
console.log(route.query.page);  // ?page=1

function goHome() { router.push("/"); }
function goBack() { router.back(); }
</script>

🏋️ Practice Task

Build a mini wiki app. Routes: / (article list), /articles/:id (single article). Create a JSON array of 5 articles in data.js. Article list page: links to each article. Article page: shows full content, has “Back to list” button. Add a NotFound page.

💡 Hint: import { useRoute } from “vue-router”. const id = route.params.id. Find article: articles.find(a => a.id === Number(id))

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *