HTML 页面上可以有多个 Svelte 组件吗?

Can I have multiple Svelte components on HTML page?

是否可以拥有一个普通的 HTML 页面并在多个位置注入 Svelte 组件,例如 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

我无法控制呈现的 HTML,它来自 CMS。所以 https://github.com/sveltejs/svelte/issues/1849 之类的东西将不起作用...我无法使用 Svelte 编译器 "compile" HTML 页面。

是的,这是可能的,在您通常使用 target: ... 安装 Svelte 应用程序的脚本中,您可以在不同的位置安装多个部分:

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

这些组件将共享同一个存储,但由于它们都是 'top level' 组件(如:它们没有共同的 parent),您不能使用 ContextAPI,也不能冒泡事件到 parent(无论如何 parent 会怎样?)

但是您可以在 window 级别收听事件:

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

如果您随后在某个组件中引发 someventsomewhere,它将被它的听众接收到。

具体设置当然取决于您的具体用例。