Raz*_*fir 6 javascript svelte svelte-3
在 Svelte 应用程序中,我有以下国家/地区数组:
let countries = [
{
name:"Alegeria",
status: "1"
},
{
name:"Bulgaria",
status :"0"
}
]
Run Code Online (Sandbox Code Playgroud)
请注意,该status
属性是一个字符串。我这样迭代数组:
{#if countries.length > 0}
<table class="table">
<thead>
<tr>
<th>Country</th>
<th class="text-right">Status</th>
</tr>
</thead>
<tbody>
{#each countries as c}
<tr>
<td>{c.name}</td>
<td class="text-right"><Switch bind:checked={Boolean(Number(c.status))} /></td>
</tr>
{/each}
</tbody>
</table>
{:else}
<p class="alert alert-danger">No countries found</p>
{/if}
Run Code Online (Sandbox Code Playgroud)
status
正如您所看到的,我尝试使用 将该属性的值转换为布尔值 this Boolean(Number(c.status))
。
我没有得到所需的转换,而是收到错误:Can only bind to an identifier (e.g.
foo) or a member expression
正如REPL显示的那样。
我究竟做错了什么?
正如错误中所述,您只能bind
使用标识符或成员表达式 - 即变量。
这是因为 abind
是双向的,如果您应用了Boolean(Number(())
它,当有人更改该输入时,svelte 不知道如何撤消这些函数以将数据“保存”回它所绑定的变量中。
如果您无法将状态变量更改为布尔值(更好的解决方案,如其他答案所建议的),则需要手动执行此双向更新。删除bind
,只拥有checked={Boolean(Number(c.status))}
,并处理输入的change
事件以从 true/false 转换回“1”或“0”,并将其保存到状态。
使用:
function handleClick(country) {
countries.find(c => c.name == country.name).status = (country.status == "1") ? "0" :"1"
}
Run Code Online (Sandbox Code Playgroud)
和
<Switch checked={Boolean(Number(c.status))} on:change={() => handleClick(c)}/>
Run Code Online (Sandbox Code Playgroud)
看到它在这个repl中工作
归档时间: |
|
查看次数: |
2359 次 |
最近记录: |