0
0
Vueframework~30 mins

Navigation guards (beforeEach, beforeEnter) in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Vue Navigation Guards with beforeEach and beforeEnter
📖 Scenario: You are building a simple Vue app with multiple pages. You want to control access to certain pages by checking if a user is logged in before allowing navigation.
🎯 Goal: Create a Vue Router setup that uses beforeEach and beforeEnter navigation guards to protect routes based on a login status.
📋 What You'll Learn
Create a Vue Router instance with routes for Home, About, and Dashboard pages
Add a boolean variable isLoggedIn to simulate user login status
Use beforeEach guard to check login status before every route
Use beforeEnter guard on the Dashboard route to restrict access
Redirect users to Home if they try to access Dashboard without login
💡 Why This Matters
🌍 Real World
Navigation guards are used in real apps to protect pages that require login or special permissions, like dashboards or user profiles.
💼 Career
Understanding navigation guards is important for frontend developers working with Vue to build secure and user-friendly web applications.
Progress0 / 4 steps
1
Set up Vue Router with routes
Create a Vue Router instance called router with three routes: { path: '/', name: 'Home' }, { path: '/about', name: 'About' }, and { path: '/dashboard', name: 'Dashboard' }.
Vue
Need a hint?

Use createRouter and createWebHistory from 'vue-router'. Define the routes array with the exact paths and names.

2
Add login status variable
Add a boolean variable called isLoggedIn and set it to false to simulate the user not being logged in.
Vue
Need a hint?

Declare isLoggedIn as a constant boolean set to false.

3
Add global beforeEach guard
Use router.beforeEach to add a global navigation guard that checks if isLoggedIn is false and the target route's name is 'Dashboard'. If so, redirect to { name: 'Home' }. Otherwise, allow navigation.
Vue
Need a hint?

Use router.beforeEach with parameters to, from, and next. Check if isLoggedIn is false and to.name is 'Dashboard'. Redirect or allow navigation accordingly.

4
Add beforeEnter guard on Dashboard route
Add a beforeEnter navigation guard to the Dashboard route inside the routes array. This guard should check if isLoggedIn is false and redirect to { name: 'Home' }. Otherwise, allow navigation.
Vue
Need a hint?

Add a beforeEnter function inside the Dashboard route object. Use the same logic as the global guard to redirect or allow navigation.