vue-pc后台管理系统:我认为的前端权限管理(八)

后台管理有不同角色,那么就有不同的权限
登录拦截,判断是否登录

router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    const token = sessionStorage.getItem("token");
    if (!token) {
      next("/login");
    } else {
      next();
    }
  }
});

通过登录接口,获取用户的权限

通过接口,获取到权限列表后,放到store里和route的meta里`

login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败!')
        this.$store.commit('setRightList', res.rights)
        this.$store.commit('setUsername', res.data.username)
        sessionStorage.setItem('token', res.data.token)
        initDynamicRoutes()
        this.$message.success('登录成功')
        this.$router.push('/home')
      })
    }
export function initDynamicRoutes() {
  const currentRoutes = router.options.routes
  const rightList = store.state.rightList
  rightList.forEach(item => {
    item.children.forEach(item => {
      const itemRule = ruleMapping[item.path]
      itemRule.meta = item.rights
      currentRoutes[2].children.push(itemRule)
    })
  })
  console.log(currentRoutes)
  router.addRoutes(currentRoutes)
}

通过返回数据,渲染菜单

通过自定义指令控制是否显示和隐藏,是否禁用

import Vue from 'vue'
import router from '@/router.js'
Vue.directive('permission', {
  inserted: function(el, binding) {
    const action = binding.value.operation
    const currentRight = router.currentRoute.meta
    if (currentRight) {
      if (currentRight.indexOf(action) === -1) {
        // 不具备权限
        const type = binding.value.effect
        if (type === 'disabled') {
          el.disabled = true//禁用
          el.classList.add('is-disabled')
        } else {
          el.parentNode.removeChild(el)//删除
        }
      }
    }
  }
})

请求拦截,再次查看是否有权限

axios.interceptors.request.use(function(req) {
  const currentUrl = req.url
  if (currentUrl !== 'login') {
    req.headers.Authorization = sessionStorage.getItem('token')
    // 当前模块中具备的权限
    const method = req.method
    // 根据请求, 得到是哪种操作
    const action = actionMapping[method]
    // 判断action是否存在当前路由的权限中
    const rights = router.currentRoute.meta
    if (rights && rights.indexOf(action) === -1) {
      // 没有权限
      alert('没有权限')
      return Promise.reject(new Error('没有权限'))
    }
  }
  return req
})
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值