路线上的Vue JS权限

时间:2018-12-18 20:35:59

标签: javascript vue.js

我有一条这样的路线:

{ path: '/testpage', component: Testpage},

我正在使用它来限制基于这样的用户角色的路由:

let roles = {"exdir":"/testpage/"};

if (loggedIn){
    // return next('/affiliatepage')
    return next(roles[user.user.role]);
}

现在,我正在尝试使其具有正确角色的用户可以访问该路由以及所有子路由。例如,如果我添加了:

/testpage/subpage

用我的方式有可能吗?

1 个答案:

答案 0 :(得分:1)

我使用Navigation Guards的方式是使用beforeEnter。 可以在here上找到有关beforeEnter的一些文档 我在下面提供了一个示例。如果条件将检查用户是否有名称,则可以检查权限级别。如果条件为真,请继续/ chat。否则,它将重定向您回到欢迎页面。

// Example of a Nav Guard
export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/', // Home
      name: 'Welcome',
      component: Welcome
    },
    {
      path: '/chat',
      name: 'Chat',
      component: Chat,
      props: true,
      //Route Guard
      beforeEnter: (to, from, next)=>{
        // Is the user name not null
        if(to.params.name){
          next() // Take you to /chat
        } else{
            // If params.name is blank or in your case, does not have permission, redirect back to the welcome page
          next({name: 'Welcome' }) 
        }
      }
    }
  ]
})

下面是一个示例方法,该方法将设置路由器的名称并允许应用继续进行/ chat

methods: {
  enterChat(){
    if(this.name){
      this.$router.push({name: 'Chat', params: {name: this.name}})
    } else{
      // They have not entered a name, so display a message telling them
    }
  }
}

希望这可以帮助您设置路警:)

相关问题