Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have multiple Svelte components on HTML page?

Tags:

svelte

Is it possible to have a plain HTML page and have Svelte components injected at multiple places, like with React Portals? So I don't want to use Svelte as a Singe Page Application (SPA), but use Svelte components on existing HTML pages. And is it possible to let the separate Svelte components to communicate with each other using the event dispatcher, and to share state using the Context API or Svelte stores?

I am not in control of the rendered HTML, it comes from a CMS. So something like https://github.com/sveltejs/svelte/issues/1849 will not work... I can't "compile" the HTML page with the Svelte compiler.

like image 317
Serge van den Oever Avatar asked Feb 06 '20 23:02

Serge van den Oever


1 Answers

Yes this is possible, in the script where you normally mount your Svelte App with target: ... you can mount several parts in different places:

new Part1({
  target: mount1
});
new Part2({
  target: mount2
});
...

These components will all share the same store, but since they are all 'top level' components (as in: they have no common parent) you cannot use the ContextAPI, nor can you bubble events to a parent (which parent would that be anyway?)

You can however listen to events on the window level:

<svelte:window on:someeeventsomewhere={}></svelte:window>

If you then raise the someventsomewhere in one of your components it will be picked up by it's listeners.

The exact setup would of course depend on your exact use case.

like image 54
Stephane Vanraes Avatar answered Nov 08 '22 02:11

Stephane Vanraes