Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1879

How can I export a function from a Svelte component that changes a value in the component?

$
0
0

I have a component called WastedTime.svelte with a value wastedTime. There's also a function to change the value to 50 (in my real code, this does an animation but this is a reduced test case for Stack Overflow).

To allow the child function to be called from a parent, I have used <script context="module"> per the Svelte docs:

<script context="module">    var wastedTime = 0;    export function changeNumber(){        console.log('changing number')        wastedTime = 50    }</script><script>    // Putting 'var wastedTime = 0' here doesn't work either</script><h1>Wasted time: {wastedTime}</h1>

The parent calls the function in the child from onMount:

<script>    import { onMount } from 'svelte';    import WastedTime, {changeNumber } from './WastedTime.svelte';    onMount(() => {        changeNumber()    });</script><WastedTime />

The problem is that since wastedTime is referred to in <script context="module">, it can't seem to change wastedTime. The exported function runs, but wastedTime stays at 0.

Copy of this on Svelte REPL

I have tried: - Putting var wastedTime = 0 in <script context="module"> - Putting var wastedTime = 0 in <script>

Neither works.

How can I export a function from a Svelte component that changes a value in the component?


Viewing all articles
Browse latest Browse all 1879

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>