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 -->
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>
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.