代码之家  ›  专栏  ›  技术社区  ›  Jimmy Kiarie

路由之前的Vue js

  •  0
  • Jimmy Kiarie  · 技术社区  · 8 年前

    我正在为我的应用程序使用laravel和vuejs,每个用户都有一个角色。现在,我想通过将用户重定向到另一个路由(如果他们无法访问页面)来限制用户按其角色访问vue路由。我正在为vuejs使用beforeRouteEnter,但出现了一个错误

    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 回复  |  直到 8 年前
        1
  •  2
  •   Kaicui    8 年前
    • 你的 can't 使用 this 在里面 beforeRouteEnter 函数,因为 before 路由更新时,组件的vm不存在。
    • 考虑到你 put role information in your vm ,您可以使用 next 要获取虚拟机,请执行以下操作:

    ```

    beforeRouteEnter(to, from, next) {
      next(vm => {
        // put your logic here
        if (vm.role === 'Admin') {
        }
     })
    }
    

    ```

    • 实际上,您应该使用 Global Router Guard put your role information in global area ,以便您可以 redirect your routing before your target component created