[Vuejs]-Vue router navigation gaurd from within the component

1πŸ‘

It is much better to put the navigation guards in routes not in pages/components and call the state getters on route file.

// /router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

// Protected Pages
import Dashboard from '@/views/dashboard'

// Public Pages
import Dashboard from '@/views/login'

Vue.use(Router)

// If you are not logged-in you will be redirected to login page
const ifNotAuthenticated = (to, from, next) => {
  if (!store.getters.loggedIn) {
    next()
    return
  }
  next('/') // home or dashboard
}

// If you are logged-in/authenticated you will be redirected to home/dashboard page    
const ifAuthenticated = (to, from, next) => {
  if (store.getters.loggedIn) {
    next()
    return
  }
  next('/login')
}

const router = new Router({
  mode: 'history',
  linkActiveClass: 'open active',
  scrollBehavior: () => ({ y: 0 }),
  routes: [
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      component: Full,
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: Dashboard,
          beforeEnter: ifAuthenticated
        },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      beforeEnter: ifNotAuthenticated
    },
    {
      path: '*',
      name: 'NotFound',
      component: NotFound
    }
  ]
})

export default router

You can also use vue-router-sync package to get the value of store values

-1πŸ‘

You can redirect the user to the home page or some other relevant page:

mounted () {
        if(vm.$store.getters.g_loginStatus === true){
             this.$router('/')
        }
}
beforeRouteEnter (to, from, next) {
    next(vm => {
        if(vm.$store.getters.g_loginStatus === true){
             next('/')
        }
    })
}

From the docs:

next: Function: this function must be called to resolve the hook. The action depends on the arguments provided to next:

  • next(): move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed.

  • next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.

  • next(β€˜/’) or next({ path: β€˜/’ }): redirect to a different location. The current navigation will be aborted and a new one will be started.

πŸ‘€Saurabh

Leave a comment