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

如何在Alpine.js循环中访问Laravel模型及索引值

问题分析

你遇到的核心问题是Blade模板语法和Alpine.js变量的执行时机冲突:

  • {{ }} 是Laravel Blade的服务器端渲染语法,页面发送到浏览器前就会完成解析;
  • i 是Alpine.js的客户端循环变量,只有浏览器加载页面后才会生成。
    服务器端无法识别客户端的i变量,导致{{ $price[i]['name'] }}无法正确解析。
解决方案

把服务器端的$price模型数据传递给Alpine.js,让客户端完成循环和数据绑定:

修正后的代码

<div x-data="{ prices: {{ json_encode($price) }} }">
    <template x-for="(priceItem, index) in prices" :key="index">
        <div class="row">
            <div class="col-md-6">
                <input type="text" 
                       :name="`prices[${index}][name]`" 
                       :value="priceItem.name">
            </div>
            <div class="col-md-6">
                <input type="number" 
                       :name="`prices[${index}][value]`" 
                       :value="priceItem.value">
            </div>
        </div>
    </template>
</div>

关键改动说明

  1. 传递服务器数据到客户端:
    用{{ json_encode($price) }}把Laravel的模型/数组转换成JSON格式,赋值给Alpine.js的prices数据变量,让客户端能直接访问。
  2. 正确使用Alpine.js循环:
    x-for直接遍历prices数组,同时获取循环项priceItem和索引index,无需单独的priceFields变量(若需动态添加字段,可在x-data里初始化prices为{{ json_encode($price) }},再添加按钮逻辑)。
  3. 客户端绑定数据:
    用:value="priceItem.name"替代Blade的{{ $price[i]['name'] }},直接通过Alpine.js变量读取数据。

动态添加字段的扩展场景(可选)

如果需要支持动态添加新价格字段,调整x-data和添加按钮即可:

<div x-data="{ prices: {{ json_encode($price) }} }">
    <!-- 循环现有价格字段 -->
    <template x-for="(priceItem, index) in prices" :key="index">
        <div class="row">
            <div class="col-md-6">
                <input type="text" 
                       :name="`prices[${index}][name]`" 
                       :value="priceItem.name">
            </div>
            <div class="col-md-6">
                <input type="number" 
                       :name="`prices[${index}][value]`" 
                       :value="priceItem.value">
            </div>
        </div>
    </template>
    <!-- 添加新字段按钮 -->
    <button type="button" @click="prices.push({ name: '', value: 0 })">添加价格字段</button>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:03:15