在此处查看示例:https://svelte.dev/repl/7fd322d6b7d641359774de781f013f45?version=3.18.1
我试图通过检查组件的ID是否与选定的ID相匹配来使组件的属性值动态化:
App.svelte
<script>
import BanjoPlayer from './BanjoPlayer.svelte'
let banjoPlayers = [{id: 1, name:'Scruggs'},{id: 2, name:'Pickelny'}]
let selectedBP = 0
</script>
<ul>
{#each banjoPlayers as bp (bp.id)}
<BanjoPlayer on:click="{e => selectedBP = bp.id}" {...bp} selected="{selectedBP === bp.id}" />
{/each}
</ul>
BanjorPlayer.svelte
export let name
export let id
export let selected
</script>
<li on:click class:selected >
{name} ({id})
</li>
我在REPL中进行了另外两次尝试:一种我认为可能可行(但不可行)的替代方案,一种可行但肯定不理想的替代方案。
答案 0 :(得分:3)
据我所知,这是一个错误,应该可以正常工作。
这显然与传播{...bp}
有关。
没有扩展的等效代码按预期工作:
<script>
import BanjoPlayer from './BanjoPlayer.svelte'
let banjoPlayers = [{id: 1, name:'Scruggs'},{id: 2, name:'Pickelny'}]
let selectedBP = 0
function isSelected(id) {
console.log(id);
return selectedBP === id
}
</script>
<h2>
The selcted player id is: {selectedBP}
</h2>
<p>
<em>How I want it to work:</em>
</p>
<ul>
{#each banjoPlayers as bp (bp.id)}
<BanjoPlayer on:click="{e => selectedBP = bp.id}" selected="{selectedBP === bp.id}" id={bp.id} name={bp.name} />
{/each}
</ul>