1
votes

How can CompOne run the function "test" in CompTwo?

CompOne.svelte

<script>
   import {test} from './CompTwo.svelte'
</script>
<!-- Some style and HTML tags for this component -->

CompTwo.svelte

<script>
   export const test = () => { console.log('testing function') }
</script>
<!-- Some style and HTML tags for this component -->
2
You can use <script context="module"> to make exports possible. But I think you are looking fot something like this. By the was: was one of my first questions too. More here: stackoverflow.com/questions/57994637/…voscausa

2 Answers

4
votes

You can run children's functions if you have an instance of this component and bind to it.

App.svelte

<script>
  import Component from './Component.svelte';   
  let comp;
</script>

<Component bind:this={comp} />
<button on:click={() => comp.test()}>Do Stuff</button>

Component.svelte

<script>
    export const test = () => console.log('testing');
</script>

Working example

1
votes

I was facing the same problem, but I just might found a workaround.

In the child component you can declare

<ChildComponent>
  <script>
    export const myFunc = () => alert('alarm... alarm..');
  </script>
</ChildComponent>

<RootComponent>
  <script>
    import ChildComponent from './ChildComponent.svelte';
    let myFunc;
  </script>

  <ChildComponent bind:myFunc={myFunc} />
  <button on:click={myFunc} >Testing Alarm</button>
</RootComponent>

See working example here: Example Svelte - Executing function on child component workaround