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

Laravel组件传参问题:集合数组双引号转义如何修复?

解决Laravel组件传递集合时引号转义的问题

问题原因

使用{{ $buildings }}传递数据时,Laravel的{{ }}语法会自动转义HTML特殊字符(包括双引号),以此防范XSS攻击,所以双引号被转换为"。

解决方案

1. 直接传递集合对象(推荐)

调用组件时,在属性前添加冒号:,直接绑定PHP变量,无需使用双大括号:

<x-panel-sum :building="$buildings"></x-panel-sum>

在组件视图文件中,可直接使用$building集合进行操作:

{{-- 遍历集合示例 --}}
@foreach($building as $item)
    <p>{{ $item->name }}</p>
@endforeach

{{-- 如需输出JSON字符串,直接调用toJson()即可 --}}
<script>
    const buildings = JSON.parse('{{ $building->toJson() }}');
</script>

2. 传递未转义的JSON字符串(特殊场景适用)

若必须传递JSON字符串而非集合对象,使用{!! !!}输出未转义的内容:

<x-panel-sum building="{!! $buildings->toJson() !!}"></x-panel-sum>

组件内拿到字符串后,可通过json_decode转换为数组使用:

// 若使用类组件,在mount方法中处理
public function mount($building)
{
    $buildings = json_decode($building, true);
}

内容的提问来源于stack exchange,提问作者Muhammad Trian Syahputra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:34:58