核心思想:尽量减少对组件的侵入性,也就是权限控制的代码剔除出来
实现
authority.vue
<template>
<div>
// 将用户权限通过作用域插槽传递出去
<slot v-if="showSlot" :permissions="rights"></slot>
</div>
</template>
<script setup lang="ts">
const props = defineProps({
permissions: {
type: [String,Array],
required: true
},
})
const rights = ref(['user-control','system-control','goods-control'])
const showSlot = computed(()=>{
// 用户无任何权限
if(!rights){
return false
}
// 没传入权限
if(!props.permissions){
return true
}
// 有传入
if(Array.isArray(props.permissions)){
return props.permissions.every((item:any)=>rights.value.includes(item))
}else {
return rights.value.includes(props.permissions)
}
})
</script>
<style lang="scss" scoped>
</style>
index.vue
<template>
<div>
<authority :permissions="['user-control','system-control']" v-slot="{permissions}">
<nut-button :disabled="!permissions.includes('system-control')" type="warning">sssss</nut-button>
</authority>
<ul>
<li class="asd">45</li>
<li>45</li>
<li>45</li>
</ul>
<div class="aaa"></div>
</div>
</template>
<script setup lang="ts" name="home">
// import { Add } from '@nutui/icons-vue'
import authority from '@/components/authority/authority.vue'
const test = ref('111')
console.log(test)
</script>
<style lang="scss" scoped>
.asd {
font-size: p2r(32);
color: green;
}
.aaa {
width: p2r(200);
height: p2r(100);
background-color: pink;
}
</style>
标签:vue,const,authority,props,组件,权限,permissions
From: https://www.cnblogs.com/zychuan/p/17686350.html