VueJS role based authentication with router

血红的双手。 提交于 2019-12-04 09:51:38

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)
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!