💚 Vue.js Beginner

What is Vue Router?

Answer

Vue Router is the official routing library for Vue.js that enables navigation between views in a SPA without full page reloads. Setup: import { createRouter, createWebHistory } from "vue-router"; const router = createRouter({ history: createWebHistory(), routes: [ { path: "/", component: HomeView }, { path: "/users/:id", component: UserView }, { path: "/admin", component: AdminView, meta: { requiresAuth: true } }, { path: "/:pathMatch(.*)*", component: NotFoundView } ] }); app.use(router);. Router outlet: <RouterView /> — where matched components render. Navigation links: <RouterLink to="/users/123">User</RouterLink> — renders as <a>, handles active class automatically. <RouterLink :to="{ name: 'UserDetail', params: { id: 123 } }">. Programmatic navigation: const router = useRouter(); router.push("/home"); router.push({ name: "UserDetail", params: { id: 123 } }); router.replace("/login"); router.go(-1);. Route params: const route = useRoute(); route.params.id; route.query.search;. Lazy loading routes: component: () => import("./views/AdminView.vue") — splits into separate chunk. Navigation guards: router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !isLoggedIn) next("/login"); else next(); });. History modes: Hash (#) or HTML5 History API (requires server configuration for direct URL access).