假设我有一个待办事项清单。每个列表项都有一个删除按钮,如果单击该按钮将从列表数组中删除该项目。现在我们就可以使用这些方法了。
1.
//store.ts
export type Item = {
text: string;
id: string;
}
export const items = writable<Item[]>();
<!-- Item.svelte -->
<script>
export let id; //I don't want to use id on the html elements. As anyone can change it from inspection tool.
export let text;
</script>
<div> {text} <button> close <button on:click={() => {
//handle click event
}}/> <div/>
<!-- Items.svelte -->
{#each items as item}
<Item id={item.id} text={text} />
{/each}
2.
<!-- Items.svelte -->
<script>
// other imports
let container;
function handleClick(node: HTMLElement){
node.onclick = (evt) => {
const target = evt.target as HTMLElement;
//handle event
}
}
<script/>
<div use:handleClick>
{#each items as item}
<Item id={item.id} text={text} />
{/each}
<div/>
我以某种方式需要获取我们用来在 {#each} 块内构建元素的对象引用。 但正如我所说,我对在 html 上使用 id 不感兴趣,我们可以用 id 来获取我们单击的元素。
只需转发事件并使用
#each
中的闭包来传递项目。
在
Item
:
<button on:click >...</button>
家长:
{#each items as item}
<Item id={item.id} text={text} on:click={() => handleClick(item)} />
{/each}