javascript - Vue JS 对路由的权限

标签 javascript vue.js

我有一条这样的路线:

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

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

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

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

现在,我正在努力使具有正确 Angular 色的用户可以访问该路由以及所有子路由。例如,如果我添加:

/testpage/subpage

以我的方式,这甚至可能吗?

最佳答案

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

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

下面是一个示例方法,它将设置路由器的名称并允许应用程序继续/something

methods: {
  enterSomething() {
    if(this.blah) {
      this.$router.push({ name: 'Something', params: { name: this.blah } })
    } else {
      // Handle else condition logic
    }
  }
}

希望这可以帮助您设置路由守卫:)

关于javascript - Vue JS 对路由的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840663/

相关文章:

javascript - 为什么溢出在我的文档中不起作用?

javascript - 方法实现差异..需要一些理解

javascript - 使用代理的 NodeJS 简单 UDP 客户端服务器应用程序

vue.js - Vue composition api 没有将绑定(bind)值更新到文本字段

vue.js - vue 语言服务器 : Elements in iteration expect to have 'v-bind:key' directives

javascript - 在 RxJS 中组合不同类型的 Observable,但只发出来自其中之一的值

javascript - JQuery:识别表格文本框列中的重复值并突出显示文本框

typescript - Vue 根据条件选择选项

javascript - 如何在同一个 Vue.js 项目中使用实时数据库和 Firestore

vue.js - 如何将 Vue slot-scope 与嵌套组件一起使用