Vue Router Vue SPAs ਲਈ ਅਧਿਕਾਰਤ client-side router ਹੈ। ਇਹ URLs ਨੂੰ components ਨਾਲ ਮੈਪ ਕਰਦਾ ਹੈ ਅਤੇ ਉਨ੍ਹਾਂ ਨੂੰ ਪੂਰੇ ਪੰਨੇ ਨੂੰ ਮੁੜ ਲੋਡ ਕੀਤੇ ਬਿਨਾਂ ਸਵੈਪ ਕਰਦਾ ਹੈ, ਅਤੇ navigation guards ਫਰਾਹਮ ਕਰਦਾ ਹੈ ਜੋ navigation ਤੋਂ ਪਹਿਲਾਂ logic (ਜਿਵੇਂ auth checks) ਚਲਾਉਂਦੇ ਹਨ।
Routes ਨੂੰ ਪਰਿਭਾਸ਼ਿਤ ਕਰਨਾ
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{ path: "/", component: Home },
{ path: "/users/:id", component: UserProfile }, // dynamic param
{ path: "/dashboard", component: () => import("./Dashboard.vue"), // lazy-loaded
meta: { requiresAuth: true } }, // attach metadata
];
const router = createRouter({ history: createWebHistory(), routes });
Navigate ਕਰਨਾ ਅਤੇ params ਪੜ੍ਹਨਾ
<template>
<RouterLink to="/users/42">Profile</RouterLink> <!-- declarative navigation -->
<RouterView /> <!-- where the matched component renders -->
</template>
<script setup>
import { useRoute, useRouter } from "vue-router";
const route = useRoute(); // read current route: route.params.id, route.query
const router = useRouter(); // navigate programmatically: router.push("/home")
</script>
Navigation guards — navigate ਕਰਨ ਤੋਂ ਪਹਿਲਾਂ logic ਚਲਾਓ
// global guard — runs before EVERY navigation (great for auth)
router.beforeEach((to, from) => {
const authed = useAuthStore().isLoggedIn;
if (to.meta.requiresAuth && !authed) {
return "/login"; // redirect: return a path (or false to cancel)
}
// returning true / nothing → allow the navigation
});
Guards to (target route) ਅਤੇ from (current) ਪ੍ਰਾਪਤ ਕਰਦੇ ਹਨ, ਅਤੇ ਅਨੁਮਤੀ ਦੇ ਸਕਦੇ ਹਨ, ਰੱਦ ਕਰ ਸਕਦੇ ਹਨ (false), ਜਾਂ redirect ਕਰ ਸਕਦੇ ਹਨ (location return ਕਰਕੇ)। meta.requiresAuth flag + global beforeEach canonical auth-gating pattern ਹੈ।
Guard levels
Global: router.beforeEach / afterEach — every navigation (auth, analytics)
Per-route: beforeEnter in the route config — specific routes
In-component: onBeforeRouteLeave — e.g. "unsaved changes, leave?" prompts
Nested routes ਅਤੇ ਹੋਰ features
{ path: "/settings", component: Settings, children: [
{ path: "profile", component: Profile }, // → /settings/profile, renders in nested <RouterView>
]}
ਨਾਲ ਹੀ: route params, query strings, named routes, scroll behavior, ਅਤੇ lazy-loaded route components code splitting ਲਈ।
ਇਹ ਮਾਇਨੇ ਰੱਖਦਾ ਹੈ
Vue Router ਕਿਸੇ ਵੀ multi-page Vue SPA ਲਈ ਜ਼ਰੂਰੀ ਹੈ — ਇਹ client-side navigation (ਤੇਜ, ਕੋਈ reloads ਨਹੀਂ), dynamic/nested routes, ਅਤੇ RouterLink/RouterView ਫਰਾਹਮ ਕਰਦਾ ਹੈ।
Navigation guards cross-cutting concerns ਲਈ ਮੁਖ ਵਿਸ਼ੇਸ਼ਤਾ ਹਨ: auth ਦੁਆਰਾ protected routes ਨੂੰ gating ਕਰਨਾ, page views ਨੂੰ log ਕਰਨਾ, ਅਤੇ unsaved forms ਤੋਂ navigation ਨੂੰ ਰੋਕਨਾ।
meta + global beforeEach pattern authentication ਲਈ ਲਗਭਗ ਹਰ real app implement ਕਰਦਾ ਹੈ।
