Svelte: transition on reactive data change
Asked Answered
I

1

6

What would be the best way to trigger an animation when a reactive variable changes? I would like to do something like this : 

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick} transition:slide>
    Click me
</button>
<p> You cliked <strong transition:fade>{count}</strong> times</p>

Which doesn't work because the <strong>node isn't removed from the DOM (I guess). So what would be the best way to have numbers fading in and out when they change?

Inartificial answered 28/6, 2020 at 17:59 Comment(0)
S
15

You can now (v3.28) use the {#key <key} directive:

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick}>
    Click me
</button>
<p> You cliked 
    {#key count}
      <strong in:fade>{count}</strong> 
    {/key}
    times</p>

old answer

Try this :

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick}>
    Click me
</button>
<p> You cliked 
    {#each [count] as c (c)}
    <strong in:fade>{c}</strong> 
    {/each}
    times</p>

REPL

Slather answered 28/6, 2020 at 19:14 Comment(4)
It is working indeed, thanks! I leave the question as seems to be a bit hacky, maybe there is a more idiomatic way to do it. I'll accept in a couple day, if not 😅Inartificial
Accepted, can't seem to find any better way for now. Thanks ! ;)Inartificial
there is now a {#key} directive. I have updated my answerRetarded
Oh that's really nice! Thanks,Inartificial

© 2022 - 2024 — McMap. All rights reserved.