I'm trying to move a svelte SPA into Sveltekit.
In my SPA, the communication schema is what I would call a "controller component" which takes care of displaying some components, listen to their events and update the app accordingly. By and large it looks like this REPL:
https://svelte.dev/repl/47bd3f8004624a3c95653b1f1aefd8ee?version=3.46.4
As you can see in this example, the sequence is fairly trivial: App state 1) App shows CompA and CommonComp App state 2) CompA triggers the doSomething function just after being mounted App state 3) App then call commonComp.setTitle and show CompB in place of CompA
In SvelteKit, I struggle to do something similar cause I don't understand how to pass data from a slotted sub component to the Component containing the slot and conversely. Anyway, this led me to this attempt:
I need 2 routes:
- PageA.svelte for when CompA & CommonComp are displayed
- PageB.svelte for when CompB & CommonComp are displayed
Because CommonComp is always visible in every states, I would think that it should resides in a __layout.svelte file.
...This took me to the draft below with the comments explaining the access problem I encounter.
/src/routes/__layout.svelte
<slot />
<CommonComp />
/src/routes/PageA.svelte
<script>
import { goto } from "$app/navigation";
import CompA from "$lib/CompA.svelte";
function handleDoSomethingFinished() {
goto("/test/pageB");
}
</script>
<CompA on:do_something_finished={handleDoSomethingFinished} />
/src/lib/CompA.svelte
<script>
import { onMount } from "svelte";
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
onMount(() => {
setTimeout(() => dispatch("do_something_finished"), 3000);
});
</script>
<p>Component A</p>
/src/routes/PageB.svelte
<script>
import CompB from "$lib/CompB.svelte";
// How to call CommonComp.setTitle function from here ?
</script>
<CompB />
/src/lib/CompB.svelte
<p>Component B</p>
/src/lib/CommonComp.svelte
<script>
let title = "Common Component";
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
export function setTitle(t) {
title = t;
dispatch("title-modified");
}
</script>
<p>{title}</p>
I guess I may have tried to share some stores and check they value into reactive statements to trigger the appropriate actions but when I'm thinking of it, I see a can of worms so I'm missing something here. Thank you for your help.