You need to enable JavaScript to run this app. 如何将Alpine JS x-for循环内的变量传递给Blade组件
优惠活动
大模型
产品
解决方案
定价
更多

如何将Alpine JS x-for循环内的变量传递给Blade组件

Alpine JS x-for循环变量传递给Blade组件的解决方案

问题根本原因

Blade 是服务端渲染阶段执行的模板引擎,而x-for是 Alpine JS 在客户端浏览器运行的逻辑:你在 Blade 中写的::title="item.title"属于 Laravel 的动态属性语法,仅支持传递服务端存在的PHP变量,此时服务端根本不存在客户端的item变量,自然无法正常取值。


可行的实现方案

方案1:透传属性+Alpine 绑定渲染

调用组件时用x-bind绑定客户端变量为HTML属性:

<template x-for="item in items" :key="item.id">
    <x-card x-bind:title="item.title" />
</template>

在card.blade.php组件内透传属性,并用Alpine语法读取渲染:

<div {{ $attributes }}>
    {{-- 直接用x-text读取绑定的title属性值 --}}
    <h3 x-text="title"></h3>
    <div class="card-content">
        {{ $slot }}
    </div>
</div>

方案2:插槽传递动态内容(更推荐)

直接把需要动态渲染的部分通过插槽传入,避免跨端变量传递的问题,兼容性更强:
父级调用写法:

<template x-for="item in items" :key="item.id">
    <x-card>
        <x-slot:title>
            <span x-text="item.title"></span>
        </x-slot:title>
        其他卡片内容
    </x-card>
</template>

card.blade.php组件写法:

<div class="card">
    <div class="card-header">
        {{ $title }}
    </div>
    <div class="card-body">
        {{ $slot }}
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 23:45:03