利用vue指令解决权限控制问题

2023-12-15 16:38:17

使用场景:在我们的系统中,有的用户有创建权限,有的用户没有创建权限。

分析:后端一般会在登录完成后将该用户的权限资源列表一次性返回给前端,因此,可以先把权限资源列表保存在vuex(pinia)中,因为这个信息我们后面会经常用到。再通过vue自定义指令来判断是否存在该权限即可。

拓展一下:vue指令的钩子函数

  • bind--指令绑定到元素之上的时候触发 只执行一次
  • unbind--指令被移出的时候触发? 只执行一次
  • update--所有节点更新的时候执行
  • componentUpdate--指令所在节点以及所有子节点都更新完成的时候执行
  • inserted--绑定指令的元素在页面展示的时候执行

vue自定义指令具体操作步骤:

import store from '@/store'

export default {
  // 绑定指令的元素在页面展示的时候执行
  inserted (el, binding, vnode) {
    const { value } = binding
    // 获取到store中的权限资源列表
    const permissionList = store.getters && store.getters.permissions

    if (value && value instanceof Array && value.length > 0) {
      const permissions = value

      const hasAnyPerms = permissionList.some(permission => {
        return permissions.includes(permission)
      })
       // 如果不存在权限,则将此节点移除
      if (!hasAnyPerms) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`need permissions! Like v-hasAnyPerms="['org:create','org:update']"`)
    }
  }
}

然后去使用并暴露这个指令

import hasAnyPerms from './hasAnyPerms'

const install = function (Vue) {
  Vue.directive('hasAnyPerms', hasAnyPerms)
}

if (window.Vue) {
  window['hasAnyPerms'] = hasAnyPerms
  Vue.use(install); // eslint-disable-line
}

hasAnyPerms.install = install
export default hasAnyPerms

最后在页面上去使用

文章来源:https://blog.csdn.net/cozy666/article/details/135019279
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。