VUE实现前后端分离的权限组件

现在做前后端分离,有时要判断有某个权限时,显示某个按钮.很多时候,这个按钮很多人就写死代码了.
我在做项目的时候,就想了一下,能否把这个东东做成一个通用的权限组件,输入URL或权限编码的地址,如果有权限,就显示,如果没有,则不显示.

  • VUE组件实现如下:
<template>
    <span v-if="showContent">
        <slot></slot>
    </span>
</template>
<script>
    import {AjaxByAll} from '../../api/api'

    export default {
        data() {
            return {
                showContent: false,


            }
        },
        methods: {
            getAuthCheckResult() {
        

                    let form = {
                        "checkUrl": this.checkUrl,
                        "methodType": this.methodType,
                        "perCode": this.perCode
                    }
                  
                    AjaxByAll('get', 'rest/common/getData/authCheckService', form).then(data => {
                        if (data.code === 200) {
                            this.showContent = data.data

                        }
                    });

            }


        },
        watch: {},
        mounted: function () {
            this.getAuthCheckResult();

        },
        props: {

            checkUrl: String,
            methodType: String,
            perCode: String
        }
    }
</script>

<style>

</style>

注意:组件里的slot一定要有,否则里面的按钮会出不来的

  • JAVA后端实现如下:
 @Override
    public Object getData(HttpServletRequest request) {
        String checkUrl = request.getParameter("checkUrl");
        if (StringUtils.hasText(checkUrl)) {
            String methodType = request.getParameter("methodType");
            AtomicReference<Set<String>> codeList = new AtomicReference<>(sysAuthApiService.getPermissionByUrl(checkUrl, methodType));
            return codeList.get().stream().anyMatch(code -> SecurityUtils.getSubject().isPermitted(code));
        } else {
            String perCode = request.getParameter("perCode");
            Assert.hasText(perCode, "权限编码不允许为空");
            return SecurityUtils.getSubject().isPermitted(perCode);
        }
    }
  • 组件使用如下:
  <auth-show per-code="oa:workflow:template:add"> <el-button type="primary" size="small" @click="openAddDialog()">新 建</el-button>
          

延伸思考,这个目前跟权限绑定在一起,后续可以考虑做成通用的,满足特定的业务场景就显示相关数据,只改后端,不用改前端的代码.
做任何事情不能只满足完成,要深化思考.

猜你喜欢

转载自blog.csdn.net/weixin_33941350/article/details/87053727