前端工作中对于权限的需求是难免的,最近项目中就有这样的需求了。
后台管理员可以新增前台成员,不通的成员具有不同的权限,有权限的人员可以看到一些操作按钮或者数据列表,反之则看不到。
那么也就是说,前端需要根据登录用户的权限来渲染指定的dom。
1、components文件下新建authorized文件夹,文件夹下新建auth.js校验权限
const checkAuth = (authName) => {
let authMap = ['admin', 'superAdmin', 'admin-1', 'landq'] // 根据实际项目需求配置
return authMap.includes(authName);
}
export default checkAuth;
这里的authMap可以是从后台动态请求的,也可以是前端配置好的,甚至可以是其它格式的数据,根据各人业务需求处理,大致思路是一样的。
2、authorized文件夹下新建index.vue
<!-- 函数式组件 -->
<script>
import checkAuthorized from './auth';
export default {
functional: true, // 函数式组件
props: {
// 接收参数
authName: {
type: String,
required: true,
default: ''
}
},
render(h, context) {
let { props, scopedSlots } = context;
return checkAuthorized(props.authName)
? scopedSlots.default({
name: props.authName
})
: null;
}
};
</script>
这里接收一个参数,登录用户名,在render函数里做进一步判断,如果权限为true则返回默认插槽里的dom,即渲染指定元素,反之返回null,不渲染
3、全局注册main.js
、、、
import Authorized from '@/components/authorized'; // 权限
Vue.config.productionTip = false;
Vue.component('Authorized', Authorized);
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
4、使用
<!-- authorized -->
<template>
<div class="authorized">
<Authorized authName="admin">
<el-button type="primary" slot-scope="data">{{
data.name
}}</el-button>
</Authorized>
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
created() {},
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {},
computed: {},
//方法集合
methods: {}
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>
当authName='admin'时,admin在authMap数组中,按钮渲染了
当authName='123'时便不会渲染