在 svelte 中对多个子组件列表实现事件处理的最佳方法是什么?

问题描述 投票:0回答:1

假设我有一个待办事项清单。每个列表项都有一个删除按钮,如果单击该按钮将从列表数组中删除该项目。现在我们就可以使用这些方法了。

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 来获取我们单击的元素。

event-handling svelte todo
1个回答
0
投票

只需转发事件并使用

#each
中的闭包来传递项目。

Item

<button on:click >...</button>

家长:

{#each items as item}
    <Item id={item.id} text={text} on:click={() => handleClick(item)} />
{/each}
© www.soinside.com 2019 - 2024. All rights reserved.