Search code examples
javascriptsvelte

Svelte - access child component's method


I have an app that simply hides content Hidden.svelte:

<script>
    let shown = false;

    function show() {
        shown = true;
    }
</script>

<svelte:options accessors={true}/>

{#if shown}
    <slot/>
{/if}

Parent App.svelte:

<script>
    import Hidden from 'Hidden';

    let child;
</script>

<Hidden bind:this={child}>
    Content
</Hidden>

<button on:click={() => child.shown = true}>Show</button>

So, child's shown can be easily set due to <svelte:options accessors={true}/> in parent

But, I want to use method show() since it can not only set shown value, but also perform some magic

Thx to Chrome's DevTools, I found that all components have an Array with props and methods, that could be accessed via some .$$.ctx, so Hidden's show() method can be called like this:

<button on:click={() => child.$$.ctx[2]()}>Show</button>

But) You know) Is there is a legal way to do it?


Solution

  • Hidden.svelte

    <script>
        let shown = false;
    
        export function show() {
            shown = true;
        }
    </script>
    
    {#if shown}
        <slot/>
    {/if}
    

    App.svelte

    <script>
        import Hidden from './Hidden.svelte';
    
        let child;
    </script>
    
    <Hidden bind:this={child}>
        Content
    </Hidden>
    
    <button on:click={() => child.show()}>Show</button>
    

    The call to child.show() can actually be simplified, but I thought this could make it harder to figure out what's going on in the example. You can do just:

    <button on:click={child.show}>Show</button>