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
this
in beforeRouteEnter
function,because before the route updates, your component's vm does not exist.next
to get your vm:beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}