svelte - 运行 代码在 for 循环中有副作用

svelte - run code with side effects inside of for loop

我有以下 Svelte 组件:

<script lang="ts">
    const tests = [ {txt: "aasdasdadss", foo: () => console.log("side ffect") }]
</script>
<div>
    {#each tests as test}
        <script>
            test.foo()
        </script>
        <div>{test.txt}</div>
    {/each}
</div>

有没有办法让test这样定义,我可以调用foo

这更接近,但它呈现 null:

<script lang="ts">
    const tests = [ {txt: "aasdaasdasdsdadss", foo: null }]
    tests[0].foo = () => {
    }
</script>
<div>
    {#each tests as test}
        {
            test.foo() || null
        }
        <div>{test.txt}</div>
    {/each}
</div>

我觉得use:action might be what you are looking for REPL

<script>
    const tests = [ {txt: "aasdaasdasdsdadss", foo: () => console.log("side ffect") }]
</script>

<div>
    {#each tests as test}        
        <div use:test.foo>{test.txt}</div>
    {/each}
</div>