每个表格行都有一个单元格,其中包含一些按需加载的“昂贵”数据;在加载之前,它显示
"?"
。单击该行的按钮后,单元格将被填充。
<table>
<tbody>
<!-- rows 1..10 -->
<tr x-data="{ foo: '?' }">
<td><span x-text="foo"></span></td>
<!-- ... -->
<td><button onclick="foo = await fetchFoo('row-11')">Load</button></td>
</tr>
<!-- rows 12... -->
</tbody>
</table>
<script>
async function fetchFoo(rowId) {
let url = `https://www.example.com/foo/${rowId}`;
let response = await fetch(url);
let result = await response.text();
return result;
}
</script>
如何将从按钮获取的数据传递到单元格?
这是一个演示,显示它不起作用;我尝试了各种语法:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js" defer></script>
<table>
<tbody>
<tr x-data="{ foo: '?' }">
<td>Hello</td>
<td><span x-text="foo"></span></td>
<td><button onclick="foo = await fetchFoo('row-1')">Load</button></td>
</tr>
<tr x-data="{ foo: '?' }">
<td>World</td>
<td><span x-text="foo"></span></td>
<td><button onclick="async () => { foo = await fetchFoo('row-2') }">Load</button></td>
</tr>
<tr x-data="{ foo: '?' }">
<td>Hi</td>
<td><span x-text="foo"></span></td>
<td><button onclick="fetchFoo('row-3')">Load</button></td>
</tr>
<!-- rows 4+... -->
</tbody>
</table>
<script>
async function fetchFoo(rowIndex) {
return new Promise(resolve => setTimeout(() => resolve(rowIndex), 1000));
}
</script>
根据文档中提供的语法(https://alpinejs.dev/start-here#building-a-counter),更新单元格内变量的正确方法是:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js" defer></script>
<table>
<tbody>
<tr x-data="{ foo1: '?' }">
<td>Hello</td>
<td><span x-text="foo1"></span></td>
<td><button x-on:click="foo1 = fetchFoo('row-1')">Load</button></td>
</tr>
<tr x-data="{ foo2: '?' }">
<td>World</td>
<td><span x-text="foo2"></span></td>
<td><button x-on:click="foo2 = fetchFoo('row-2')">Load</button></td>
</tr>
<tr x-data="{ foo3: '?' }">
<td>Hi</td>
<td><span x-text="foo3"></span></td>
<td><button x-on:click="foo3 = fetchFoo('row-3')">Load</button></td>
</tr>
<!-- rows 4+... -->
</tbody>
</table>
<script>
async function fetchFoo(rowIndex) {
return new Promise(resolve => setTimeout(() => resolve(rowIndex), 1000));
}
</script>