1
votes

I use vuex from centralized state management in my vuex store.js i store the login status as a boolean value like below

export const store = new Vuex.Store({
state: {
loggedIn: false,
userName: 'Guest',
error: {
    is: false,
    errorMessage: ''
}
},
getters: {
g_loginStatus: state => {
    return state.loggedIn;
},
g_userName: state => {
    return state.userName;
},
g_error: state => {
    return state.error;
}
}
)};

When the user logs in i set the loginstatus to true and remove the login button and replace it with log out button everything works fine but the problem is when the user is logged in and if i directly enter the path to login component in the search bar i am able to navigate to login page again I want to preent this behaviour If the uses is logged in and searches for the path to loginpage in the searchbar he must be redirected to home page

I have tried using beforeRouteEnter in the login component But we do not have acess to the this instance since the component is not yet loaded So how can i check for login status from my store

my script in login.vue

script>

export default{
    data(){
        return{
            email: '',
            password: ''
        };
    },
    methods: {
        loginUser(){
            this.$store.dispatch('a_logInUser', {e: this.email, p: this.password}).then(() =>{
                this.$router.replace('/statuses');

            });
        }
    },
    beforeRouteEnter (to, from, next) {
        next(vm => {
            if(vm.$store.getters.g_loginStatus === true){
                 //what shall i do here
            }
        })
    }
}

2

2 Answers

1
votes

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

0
votes

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.