我正在为我的应用程序使用laravel和vuejs,每个用户都有一个角色。现在,我想限制用户通过他们的角色访问vue路由,如果他们无法访问该页面,则将其重定向到另一个路由。我使用beforeRouteEnter for vuejs但我收到错误
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('/')
}
}
我收到此错误
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
答案 0 :(得分:1)
App
can't
使用this
函数,因为beforeRouteEnter
路由更新,您的组件的vm不存在。before
,您可以使用put role information in your vm
获取您的虚拟用语:```
next
```
beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}
,以便您可以put your role information in global area