注意:核心思想是使用插槽的方式,控制显示隐藏
第一步,创建一个名为Authority.vue的文件,并编写以下代码:
- <template>
- <div>
- <slot v-if="hasPermission">{{ $slots.default }}slot>
- div>
- template>
-
- <script>
- export default {
- props: {
- role: {
- type: String,
- default: ''
- },
- permissions: {
- type: Array,
- default: () => []
- },
- permission: {
- type: String,
- default: ''
- }
- },
- computed: {
- hasPermission() {
- // 根据角色和权限判断是否有权限
- if (this.role === 'admin') {
- return true; // 管理员拥有所有权限
- }
- return this.permissions.includes(this.permission);
- }
- }
- };
- script>
这里使用了插槽来显示具有权限的内容。hasPermission属性根据传入的角色和权限数据决定是否显示插槽内容。
然后,在使用该组件的地方,可以按照以下方式进行使用:
- <template>
- <div>
- <authority :role="'admin'">
- <button>管理员才能看到的按钮button>
- authority>
-
- <authority
- :role="'user'"
- :permissions="['view:user']"
- :permission="'view:user'"
- >
- <div>普通用户只有在拥有查看用户权限时才能看到的内容div>
- authority>
-
- <authority
- :role="'user'"
- :permissions="['edit:user']"
- :permission="'view:user'"
- >
- <div>普通用户只有在拥有编辑用户权限时才能看到的内容div>
- authority>
- div>
- template>
-
- <script>
- import Authority from '@/components/Authority.vue';
-
- export default {
- components: {
- Authority
- }
- };
- script>
这里展示了三个使用场景,其中第一个authority组件中,传入role='admin',表示只有管理员可以看到插槽中的内容,因此按钮会被显示。第二个和第三个authority组件中,传入role='user',表示是普通用户,但是在拥有view:user或edit:user权限时,才能看到插槽中的内容。
通过这种方式,你可以灵活地根据具体情况来进行组合和使用,来实现更丰富的权限控制逻辑。