earlyBeard
earlyBeard

Reputation: 41

Remove Component after time itself from DOM

Hello Guy's so I've created in Svelte a Component, which should itself remove after a time.

    <script>
    export let time;
</script>

<div class="notif">
  </div>

<style>
    
    
</style>

How would I archive that?

Upvotes: 1

Views: 2095

Answers (1)

Corrl
Corrl

Reputation: 7721

From https://github.com/sveltejs/svelte/issues/3089

The difference in Svelte 3 is that component's can't self-destruct — there's no equivalent of this.destroy(). If a component can't destroy itself, that implies that some parent or controller must destroy it, ...

To destroy the component either an {#if} block could be used or calling component.$destroy()

A REPL with the examples

<script>
    import Comp1 from './Comp1.svelte'
    import Comp2 from './Comp2.svelte'

    let showComp = true

    let compRef
</script>

{#if showComp}
<Comp1 bind:showComp time={1500} />
{/if}

<Comp2 bind:this={compRef} self={compRef} time={1500}/>
Comp1
<script>
    import {onDestroy} from 'svelte'

    export let showComp, time

    setTimeout(() => {
        showComp = false
    }, time)

    onDestroy(() => {
        console.log('successfully destroyed Comp1')
    })

</script>

COMP 1
Comp2
<script>
    import {onDestroy} from 'svelte'
    
    export let self, time

    setTimeout(() => {
        self.$destroy()
    }, time)

    onDestroy(() => {
        console.log('successfully destroyed Comp2')
    })
</script>

COMP 2

Upvotes: 4

Related Questions