当前位置:   article > 正文

vue 页面权限控制_vue控制页面权限

vue控制页面权限

(一)通过配置路由 meta 以及路由守卫来实现

在每一个路由的 meta 属性里,将能访问该路由的角色添加到 roles 里。用户每次登陆后,获取用户的角色。

然后在访问页面时,把路由的 meta 属性和用户的角色进行对比,如果用户的角色在路由的 roles 里,那就是能访问,如果不在就拒绝访问 或者 弹出提示

代码:

  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import HelloWorld from '@/components/HelloWorld'
  4. import NoAccess from '@/components/NoAccess'
  5. Vue.use(Router)
  6. const router = new Router({
  7. routes: [
  8. {
  9. path: '/',
  10. name: 'HelloWorld',
  11. component: HelloWorld,
  12. meta: {
  13. roles: ['admain', 'users']
  14. }
  15. },
  16. {
  17. path: '/NoAccess',
  18. name: 'NoAccess',
  19. component: NoAccess
  20. }
  21. ]
  22. })
  23. // 模拟角色
  24. const userRole = 'users'
  25. // router 是 Router 的实例
  26. router.beforeEach((to, from, next) => {
  27. // 说明该路由有权限校验
  28. if (to.meta.roles) {
  29. // 校验身份
  30. if (to.meta.roles.includes(userRole)) {
  31. next()
  32. } else {
  33. next('/NoAccess')
  34. }
  35. } else { // 没权限直接跳过
  36. next()
  37. }
  38. })
  39. export default router

(二)登录验证

网站一般只要登陆过一次后,接下来该网站的其他页面都是可以直接访问的,不用再次登陆。

我们可以通过 token 或 cookie 来实现,下面用代码来展示一下如何用 token 控制登陆验证

也是通过 路由守卫 beforeEach 来实现的

  1. router.beforeEach((to, from, next) => {
  2. // 如果有token 说明该用户已登陆
  3. if (localStorage.getItem('token')) {
  4. // 在已登陆的情况下访问登陆页会重定向到首页
  5. if (to.path === '/login') {
  6. next({path: '/'})
  7. } else {
  8. next({path: to.path || '/'})
  9. }
  10. } else {
  11. // 没有登陆则访问任何页面都重定向到登陆页
  12. if (to.path === '/login') {
  13. next()
  14. } else {
  15. next(`/login?redirect=${to.path}`)
  16. }
  17. }
  18. })

(三)动态路由

用户根据不同的角色生成相应的路由列表

router.addRoutes(routerArrayConfig)

代码:

  1. const router = new Router({
  2. routes: [
  3. {
  4. path: '/login',
  5. name: 'login',
  6. component: () => import('../components/Login.vue')
  7. },
  8. {
  9. path: '/',
  10. redirect: '/home'
  11. component: () => import('../components/Home.vue')
  12. },
  13. ]
  14. })

与下方相同:

  1. const router = new Router({
  2. routes: [
  3. {
  4. path: '/',
  5. redirect: '/home'
  6. },
  7. ]
  8. })
  9. router.addRoutes([
  10. {
  11. path: '/login',
  12. name: 'login',
  13. component: () => import('../components/Login.vue')
  14. }
  15. ])

所以可能后端返回 一个列表,前端通过数组循环等处理方式,变成真正的路由导入

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号