You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue模板中如何用hasPermissionTo判断角色权限并控制导航显示

解决方案

1. 定义权限检查函数

在组件的<script setup>中添加hasPermissionTo函数,用于判断当前角色是否拥有指定权限:

<script setup>
import { Link } from "@inertiajs/inertia-vue3"
import { defineProps } from "vue";

const props = defineProps({
    is_admin: Boolean,
    role: Object,
});

// 检查角色是否拥有目标权限
const hasPermissionTo = (targetPermission) => {
    // 管理员默认拥有所有权限(可根据业务需求调整或删除此逻辑)
    if (props.is_admin) return true;
    
    // 检查角色权限列表中是否存在目标权限
    // 注:假设权限对象的name字段存储权限标识(如"admin.index"),若你的字段是slug或其他,需对应修改
    return props.role?.permissions?.some(permission => permission.name === targetPermission) || false;
};
</script>

2. 在模板中控制链接显示

给Dashboard的<Link>标签添加v-if指令,通过调用hasPermissionTo函数控制链接是否渲染:

<Link 
    v-if="hasPermissionTo('admin.index')"
    class="flex items-center mt-4 py-2 px-6 bg-gray-700 bg-opacity-25 text-gray-100" 
    :href="route('admin.index')" 
>
    <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
         <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M11 3.055A9.001 9.001 0 1020.945 13H11V3.055z" />
         <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M20.488 9H15V3.512A9.025 9.025 0 0120.488 9z" />
    </svg>
    <span class="mx-3">Dashboard</span>
</Link>

补充说明

  • 如果权限标识存储在其他字段(如slug),请将permission.name替换为对应的字段名。
  • 可选链?.的作用是避免role或permissions为空时触发报错,提升代码健壮性。

内容的提问来源于stack exchange,提问作者Nitin Pujari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:35:33