【问题标题】:How to set x-model and name of Input field inside x-for in alpine js?如何在 alpine js 中的 x-for 中设置 x-model 和 Input 字段的名称?
【发布时间】:2021-05-24 14:39:24
【问题描述】:

我在使用 alpine js 保存数据时遇到问题。 我在 for 循环中有一个表单。但是,我无法设置 x-model 的索引和表单输入的名称。

HTML:

<template x-for="(price, index) in prices">
    <tr data-id="price.id">
        <td class="text-right">
            <input type="text" class="form-control" x-bind:name="record.items[${index}].batch" x-model="record.items[${index}].batch">
        </td>
    </tr>
</template>

JavaScript

record: {
    items: [],
}

我收到了这个错误。 Uncaught ReferenceError: index is not defined.

如何解决?

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    我创建了一个CodePen,说明如何在x-for 循环中使用index 并引用项目。

    在您的代码中使用${index} 对我来说似乎是错误的。你应该可以像[index]一样使用它:

    <div x-data="{ prices: myPrices, items: record.items }">
          <template x-for="(price, index) in prices">
            <div>
                <span x-text="price.id"></span>
                <input type="text" x-bind:name="items[index]" x-bind:placeholder="items[index]">
            </div>
          </template>
    </div>
    

    有关所有详细信息,请参阅完整的 CodePen。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2021-05-08
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多