Svelte:App Constructor 的第二次实例化覆盖了第一次实例化,Props 进入商店问题?

Svelte: Second Instantiation of App Constructor Overwrites the First Instantiation, Props Going into Stores the Problem?

您好 Sveltermeisters,

问题: 我正在尝试在同一页面上初始化 App 的两个实例。应用程序在 main.js 文件中的页面上作为全局变量公开,如下所示:

//main.js
import App from './components/App.svelte'
window.App = App

然后在 html 页面中初始化两个应用程序实例

<!–– index.html  ––> 
<button id="cta-button>CTA</button>
<button id="cta-button-2>CTA</button>

<!–– app.js is built and deployed as remote resource  ––> 
<script type="text/javascript" src="https://path.to/app.js"></script>
<script>
  const app = new App({
    target: document.querySelector('body'),
    props: {
      targetButtonIdToShowFormModal: "cta-button",
      iGetDroppedIntoAStore1: "some value",
      iGetDroppedIntoAStore2: "some value",
      iGetDroppedIntoAStore3: "some value"
    }
  })
  const app2 = new App({
    target: document.querySelector('body'),
    props: {
      targetButtonIdToShowFormModal: "cta-button-2",
      iGetDroppedIntoAStore1: "some different value",
      iGetDroppedIntoAStore2: "some different value",
      iGetDroppedIntoAStore3: "some different value"
    }
  })
</script>

奇怪的是:第二个app的props会覆盖第一个app的props,而且无论打开哪个app,每个app的状态始终保持同步。

我的断言:由于道具被转储到商店中,第二个实例正在覆盖第一个实例。由于每个应用都引用同一组商店,因此它们的数据始终保持同步。

这是真的吗?如果是这样,我如何设计我的商店以使其数据保持独立?

尝试为每个 App 个实例创建一个商店实例,您可以使用 context setContext & getContext.

Associates an arbitrary context object with the current component and the specified key. The context is then available to children of the component (including slotted content) with getContext.


Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.

(Example)