0

I am using laravel and vuejs for my app and every user has a role. Now I want to restrict users to access vue routes by their roles by redirecting them to another route if they can't access the page. I am using beforeRouteEnter for vuejs but I am getting an error

data() {
    return{
      role: '',
    }
  },
mounted() {
    axios.post('/getRole')
    .then((response) => this.role = response.data)
    .catch((error) => this.errors = error.response.data.errors)
  },

beforeRouteEnter (to, from, next) {
    if (this.role === 'Admin') {
      next()
    }else {
      next('/')
    }
}

I am getting this error

app.js:72652 TypeError: Cannot read property 'role' of undefined
    at beforeRouteEnter (app.js:90653)
    at routeEnterGuard (app.js:72850)
    at iterator (app.js:72690)
    at step (app.js:72464)
    at runQueue (app.js:72472)
    at app.js:72726
    at step (app.js:72461)
    at app.js:72465
    at app.js:72711
    at app.js:72539
1
  • have your problem be solved? Commented Apr 27, 2018 at 9:00

1 Answer 1

2
  • you can't use this in beforeRouteEnter function,because before the route updates, your component's vm does not exist.
  • in consideration of you put role information in your vm, you can use next to get your vm:
beforeRouteEnter(to, from, next) {
  next(vm => {
    // put your logic here
    if (vm.role === 'Admin') {
    }
  })
}
  • actually,you should use the Global Router Guard ,and put your role information in global area,so that your can redirect your routing before your target component created
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.