Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to perform svelte transition without a if block?

  <button on:click={() => (visible = !visible)}>Toggle</button>

  {#if !visible}
    <QuizArea
      transition:slide
      on:score={e => {
        playerScore = e.detail.score;
      }} />
  {/if}

My question is can I use the transition without toggling the visibility?

like image 978
Manan Joshi Avatar asked Nov 27 '19 02:11

Manan Joshi


1 Answers

Using a {#key} block:

<script>
import { fly } from "svelte/transition"
let unique = {}

function restart() {
  unique = {} // every {} is unique, {} === {} evaluates to false
}
</script>

{#key unique}
  <h1 in:fly={{x: 100}}>Hello world!</h1>
{/key}

<button on:click={restart}>Restart</button>

REPL

{#key} was introduced in Svelte v3.28, before that you needed to use a keyed {#each} block with only one item

When the key changes, svelte removes the component and adds a new one, therefor triggering the transition.

Using { create_in_transition } from "svelte/internal"

<script>
    import { fly } from "svelte/transition"
    import { create_in_transition } from "svelte/internal"
    
    let element;
    let intro
    
    function animate() {
        if (!intro) {
            intro = create_in_transition(element, fly, {x: 100});   
        }   
        intro.start();

    }
</script>

<h1 bind:this={element}>Hello world!</h1>
<button on:click={animate}>Go</button>

REPL

Has a similar effect, but instead of removing the previous component and creating a new one, this method re-uses the same instance.

But using internal api's is dangerous as these may change when you update svelte.
If you decide to use this, add a line to your project Readme.md mentioning which internal api's you used and why.
Try to write it using other methods when you can.

like image 196
Bob Fanger Avatar answered Oct 06 '22 01:10

Bob Fanger