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

Laravel Blade组件使用命名slot报$svg未定义异常问题排查

Laravel Blade 命名插槽 Undefined variable 报错解决方案

报错核心原因

你将命名插槽对应的变量错误声明到了@props中,触发了Blade的变量注入逻辑冲突:

  • @props仅用于接收组件调用时标签上直接传递的属性参数,比如示例中的route="home"就属于这类参数
  • 用<x-slot name="xxx">传递的命名插槽,Blade会自动生成对应的$xxx变量,无需在@props中额外声明

你在@props里加入'svg'后,Blade会优先从组件标签的属性中查找svg参数,你没有传递该属性,所以$svg被初始化为未定义状态,自动生成的插槽变量被覆盖,就出现了报错。看起来矛盾的「Possible typo $svg - Did you mean $svg?」提示,是调试器检测到作用域内存在被遮蔽的同名插槽变量导致的。

修复方案

方案1(仅使用插槽传svg)

直接修改组件的@props声明,移除'svg'项即可:

@props([
    'route',
])

<a href="{{ route($route) }}" class="w-full focus:text-teal-500 hover:text-teal-500 justify-center inline-block text-center pt-2 pb-1">
    <div {{ $svg->attributes->class(['inline-block']) }}>
        {{ $svg }}
    </div>
    <span class="tab tab-home block text-xs">{{ $slot }}</span>
</a>

方案2(同时支持属性传svg、插槽传svg)

如果需要兼容两种传参方式,给@props中的svg设置默认值为null,手动合并两种来源的参数即可:

@props([
    'route',
    'svg' => null,
])

@php
// 优先取属性传递的svg,属性为空则取插槽内容
$svg = $svg ?? $slots->get('svg');
@endphp

<a href="{{ route($route) }}" class="w-full focus:text-teal-500 hover:text-teal-500 justify-center inline-block text-center pt-2 pb-1">
    <div {{ $svg->attributes->class(['inline-block']) }}>
        {{ $svg }}
    </div>
    <span class="tab tab-home block text-xs">{{ $slot }}</span>
</a>

内容的提问来源于stack exchange,提问作者Michael Krøyserth-Simsø

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:21:01