学无先后,达者为师

网站首页 Vue 正文

【Vue项目必备】如何通过权限优雅地控制按钮的显示

作者:weixin_43385047 更新时间: 2022-01-02 Vue

前端项目中通常会有很多 让不同权限的用户,看到的内容、可实现的操作不同的 需求。

作为优雅的前端工作者,如何避免每次都在代码里重复的写判断的冗余代码?

第一步

…/utils/auth.js 文件位置

//获取当前客户权限
export function getCurrentAuthority(){
    ...
    return ["admin"]
}

//校验权限
export function check(authority = []){ 	//authority:符合什么权限的条件
    let current = getCurrentAuthority();	//得到当前客户有多少权限 
    return current.some(item => authority.includes(item));	//判断是否符合权限 
}

//登录校验
export function isLogin(){
    const current = getCurrentAuthority();
    return current && current[0] !== "guest";    
}

第二步

进行自定义指令控制

思路:

接收自定义指令 binding 中传递的参数,通过 check 函数进行校验,校验未通过时,获取当前指令所在节点的父节点,来删除掉当前节点,实现权限控制。

…/directives/auth.js 文件位置

import { check } from '../utils/auth.js';

function install(Vue, options = {}) {
    Vue.directive(options.name || 'auth', {
        inserted(el, binding) {
            if (!check(binding.value)) {
                el.parentNode && el.parentNode.removeChild(el);
            }
        }
    })
}

export default { install }

指令注册
…/main.js 文件位置


import auth from './directives/auth.js'
Vue.use(auth)

指令使用:

	<any-components v-auth="['admin']"></any-components>

原文链接:https://blog.csdn.net/weixin_43385047/article/details/122111210

栏目分类
最近更新