0
0
Vueframework~10 mins

Navigation guards (beforeEach, beforeEnter) in Vue - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a global navigation guard that runs before each route change.

Vue
router.[1]((to, from, next) => {
  console.log('Navigation started');
  next();
});
Drag options to blanks, or click blank then click option'
AonReady
BbeforeEnter
CafterEach
DbeforeEach
Attempts:
3 left
💡 Hint
Common Mistakes
Using beforeEnter instead of beforeEach for global guards
Using afterEach which runs after navigation
Using onReady which is unrelated
2fill in blank
medium

Complete the code to add a route-specific guard that runs before entering the '/dashboard' route.

Vue
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    [1]: (to, from, next) => {
      if (isLoggedIn()) next();
      else next('/login');
    }
  }
];
Drag options to blanks, or click blank then click option'
AbeforeEnter
BbeforeEach
CafterEnter
DbeforeRouteEnter
Attempts:
3 left
💡 Hint
Common Mistakes
Using beforeEach inside route config (only global)
Using afterEnter which does not exist
Using beforeRouteEnter which is a component guard
3fill in blank
hard

Fix the error in the global guard code to correctly call the next function.

Vue
router.beforeEach((to, from, [1]) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login');
  } else {
    next();
  }
});
Drag options to blanks, or click blank then click option'
Anext
Bcontinue
Cproceed
Dgo
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect function names like go or proceed
Not calling next at all causing navigation to hang
4fill in blank
hard

Fill both blanks to create a global guard that blocks navigation to '/admin' if the user is not an admin.

Vue
router.[1]((to, from, next) => {
  if (to.path === '/admin' && !userIsAdmin()) {
    next({ path: [2] });
  } else {
    next();
  }
});
Drag options to blanks, or click blank then click option'
AbeforeEach
BafterEach
C/login
D/home
Attempts:
3 left
💡 Hint
Common Mistakes
Using afterEach which runs after navigation
Redirecting to wrong path like '/home'
5fill in blank
hard

Fill all three blanks to create a route with a beforeEnter guard that checks if the user is logged in and redirects to '/login' if not.

Vue
const routes = [
  {
    path: '/profile',
    component: Profile,
    [1]: (to, from, next) => {
      if (![2]()) {
        next({ path: [3] });
      } else {
        next();
      }
    }
  }
];
Drag options to blanks, or click blank then click option'
AbeforeEnter
BisLoggedIn
C'/login'
DbeforeEach
Attempts:
3 left
💡 Hint
Common Mistakes
Using beforeEach inside route config
Not calling next properly
Redirecting to wrong path or missing quotes