Vue js beforeRouteEnter

时间:2018-04-27 05:58:47

标签: laravel vue.js vue-router

我正在为我的应用程序使用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

1 个答案:

答案 0 :(得分:1)

  • App can't使用this函数,因为beforeRouteEnter路由更新,您的组件的vm不存在。
  • 考虑到您before,您可以使用put role information in your vm获取您的虚拟用语:

```

next

```

  • 实际上,您应该使用Global Router GuardbeforeRouteEnter(to, from, next) { next(vm => { // put your logic here if (vm.role === 'Admin') { } }) } ,以便您可以put your role information in global area