1

我在使用 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.

如何解决这个问题?

4

1 回答 1

0

我创建了一个CodePen 来说明如何使用循环index内部x-for和引用项。

在你的代码中使用${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。

于 2021-02-22T12:17:42.280 回答