Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte executing function on child component

Tags:

svelte

I am new to svelte, I would like to know if there is way to pass data from parent to nested child component and execute function on child component.

Below is the code for App.svelte

<script>
  import Outer from "./Outer.svelte";
  let dataMap = {};
  function handleIncommingMessage(message) {
    dataMap[message.key] = message;
  }
</script>
<Outer {dataMap} />

This is the Outer Component Outer.svelte

<script>
    import Inner from './Inner.svelte';
    export let dataMap;
</script>

<Inner {dataMap}/>

This is the inner Component Inner.svelte

<script>
    export let dataMap;
    function executeChildFunction() {
        //Process received dataMap
    }
</script>

<div>
<!-- Display processed dataMap -->
</div>

I want to run the executeChildFunction in the Inner.svelte. I know to createEventDispatcher in Inner.svelte and execute a function in App.svelte. But I would like to know if the other way is possible, createEventDispatcher in Parent and execute function in child. Kindly let me know. Thank You.

like image 955
Kanan Jarrus Avatar asked May 21 '26 05:05

Kanan Jarrus


1 Answers

Make it reactive:

<script>
    export let dataMap;

    function executeChildFunction(dataMap) {
        //Process received dataMap
    }

    $: executeChildFunction(dataMap);
</script>

<div>
    <!-- Display processed dataMap -->
</div>
like image 184
voscausa Avatar answered May 25 '26 16:05

voscausa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!