并非所有应用状态都属于应用的组件层次结构。 有时,你的值需要由多个不相关的组件或常规 JavaScript 模块访问。
英Not all application state belongs inside your application's component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.
在 Svelte,我们通过存储做到这一点。 存储只是一个具有 subscribe 方法的对象,该方法允许感兴趣的各方在存储值发生变化时收到通知。 在 App.svelte 中,count 是一个存储,我们在 count.subscribe 回调中设置 countValue。
英In Svelte, we do this with stores. A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes. In App.svelte, count is a store, and we're setting countValue in the count.subscribe callback.
单击 stores.js 选项卡可查看 count 的定义。 它是一个可写存储,这意味着除了 subscribe 之外,它还有 set 和 update 方法。
英Click the stores.js tab to see the definition of count. It's a writable store, which means it has set and update methods in addition to subscribe.
现在转到 Incrementer.svelte 选项卡,以便我们可以连接 + 按钮:
英Now go to the Incrementer.svelte tab so that we can wire up the + button:
tsfunctionincrement () {count .update ((n ) =>n + 1);}
单击 + 按钮现在应该会更新计数。 对 Decrementer.svelte 执行相反操作。
英Clicking the + button should now update the count. Do the inverse for Decrementer.svelte.
最后,在 Resetter.svelte 中,实现 reset:
英Finally, in Resetter.svelte, implement reset:
tsfunctionreset () {count .set (0);}