Navigation Guards का उपयोग
Guards navigation से पहले या बाद में चलते हैं, इसलिए आप route changes block, redirect, या log कर सकते हैं।
In this page:
Syntax
router.beforeEach((to, from) => {
if (condition) {
return '/redirect-path';
}
// returning nothing allows navigation
});
Navigation Guards
router.beforeEach((to, from) => ...) हर navigation से पहले चलता है और cancel करने के लिए false, redirect करने के लिए एक route location, या continue करने के लिए कुछ नहीं return कर सकता है।
Per-route beforeEnter और in-component guards भी exist करते हैं। guards drive करने के लिए requiresAuth जैसे meta fields इस्तेमाल करें।
Note:
User को redirect करने के लिए एक guard से एक route location return करें।
उदाहरण: Navigation guards
<!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 loggedIn = false;
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ path: "/", component: { template: "<p>Public home</p>" } },
{ path: "/login", component: { template: "<p>Please log in</p>" } },
{ path: "/admin", meta: { requiresAuth: true }, component: { template: "<p>Secret admin</p>" } },
],
});
router.beforeEach((to) => {
if (to.meta.requiresAuth && !loggedIn) return "/login";
});
Vue.createApp({}).use(router).mount("#app");
router.push("/admin").then(async () => {
await Vue.nextTick();
console.log("landed on:", router.currentRoute.value.path, "-", document.querySelector("p").textContent);
});
</script>
</body>
</html>
<!-- Output:
Rendered: Please log in
console: landed on: /login - Please log in
-->
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. #}
आम गलतियां
- Redirect loops बनाना
- old next() callback को गलत तरीके से इस्तेमाल करना
- सिर्फ client पर protect करना
चैप्टर सारांश
- beforeEach navigation से पहले चलता है
- Block या redirect करने के लिए false या एक location return करें
- meta fields rules drive करते हैं
- Server भी secure करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: