VueJS role based authentication with router VueJS role based authentication with router vue.js vue.js

VueJS role based authentication with router


I will say that you should handle this in the login action.

You identify the user role at the login action, then save the role as a state and redirect to the user page based on the user role, doing this in the same method/callback.

Other approach can be to have a the user role as a computed value in the login Vue component and handle the user role changes

computed: {  userRole: function () {    let role = this.$store.state.userRole    if(role === 'student'){      router.push('/student')    } else if(role === 'admin'){      router.push('/admin')    }    return role   }}

but I think the first approach is better.

You don't have to pass the router (this.$router) to the store action. You can return a Promise from the login store action:

In Store.js:

login({commit},authData){  return new Promise(resolve => {    axios.post('http://localhost/laravel_back/public/api/login',authData)    .then(res => {      console.log("Back-end Response",res);      commit('authUser',{        token:res.data[0].token,        userName:res.data[1][0].fname,        id:res.data[2].id,        type:res.data[3][0].role_id      })      //get the role      let role = res.data[3][0].role_id      resolve(role);    }).catch(error => console.log(error))  })}

In component:

onLogin () {  this.$store.dispatch('login', {    email: this.email,    password: this.password  }).then(role => {    this.$router.push('/'+role)  });}