svelte/store
模块导出用于创建 readable、writable 和 derived 存储的函数。
英The svelte/store
module exports functions for creating readable, writable and derived stores.
请记住,你不必使用这些函数来享受组件中的 反应式 $store
语法。 任何正确实现 .subscribe
、取消订阅和(可选).set
的对象都是有效的存储,并且可以使用特殊语法和 Svelte 的内置 derived
家存储 来工作。
英Keep in mind that you don't have to use these functions to enjoy the reactive $store
syntax in your components. Any object that correctly implements .subscribe
, unsubscribe, and (optionally) .set
is a valid store, and will work both with the special syntax, and with Svelte's built-in derived
stores.
这使得封装几乎所有其他反应式状态处理库以在 Svelte 中使用成为可能。 阅读有关 存储合同 的更多信息,了解正确的实现是什么样的。
英This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the store contract to see what a correct implementation looks like.
writablepermalink
导出片段: svelte/store#writable
创建一个存储的函数,该存储具有可以从 'outside' 组件设置的值。 它使用附加的 set
和 update
方法创建为对象。
英Function that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional set
and update
methods.
set
是一种采用一个参数(即要设置的值)的方法。 如果存储值尚未等于参数的值,则存储值将设置为参数的值。
英set
is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.
update
是一种采用一个回调参数的方法。 该回调将现有的存储值作为其参数,并返回要设置到存储中的新值。
英update
is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.
ts
import {writable } from 'svelte/store';constcount =writable (0);count .subscribe ((value ) => {console .log (value );}); // logs '0'count .set (1); // logs '1'count .update ((n ) =>n + 1); // logs '2'
ts
import {writable } from 'svelte/store';constcount =writable (0);count .subscribe ((value ) => {console .log (value );}); // logs '0'count .set (1); // logs '1'count .update ((n ) =>n + 1); // logs '2'
如果将函数作为第二个参数传递,则当订阅者数量从零到一(但不是从一到二等)时将调用该函数。 该函数将传递一个 set
函数,该函数更改存储的值,以及一个 update
函数,该函数的工作方式类似于存储上的 update
方法,采用回调来根据存储的旧值计算存储的新值。 它必须返回一个 stop
函数,当订阅者计数从 1 变为 0 时调用该函数。
英If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a set
function which changes the value of the store, and an update
function which works like the update
method on the store, taking a callback to calculate the store's new value from its old value. It must return a stop
function that is called when the subscriber count goes from one to zero.
ts
import {writable } from 'svelte/store';constcount =writable (0, () => {console .log ('got a subscriber');return () =>console .log ('no more subscribers');});count .set (1); // does nothingconstunsubscribe =count .subscribe ((value ) => {console .log (value );}); // logs 'got a subscriber', then '1'unsubscribe (); // logs 'no more subscribers'
ts
import {writable } from 'svelte/store';constcount =writable (0, () => {console .log ('got a subscriber');return () =>console .log ('no more subscribers');});count .set (1); // does nothingconstunsubscribe =count .subscribe ((value ) => {console .log (value );}); // logs 'got a subscriber', then '1'unsubscribe (); // logs 'no more subscribers'
请注意,当 writable
被销毁时(例如刷新页面时),其值会丢失。 但是,你可以编写自己的逻辑来将值同步到例如 localStorage
。
英Note that the value of a writable
is lost when it is destroyed, for example when the page is refreshed. However, you can write your own logic to sync the value to for example the localStorage
.
readablepermalink
导出片段: svelte/store#readable
创建一个不能从 'outside' 设置值的存储,第一个参数是存储的初始值,readable
的第二个参数与 writable
的第二个参数相同。
英Creates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to readable
is the same as the second argument to writable
.
ts
import {readable } from 'svelte/store';consttime =readable (newDate (), (set ) => {set (newDate ());constinterval =setInterval (() => {set (newDate ());}, 1000);return () =>clearInterval (interval );});constticktock =readable ('tick', (set ,update ) => {constinterval =setInterval (() => {update ((sound ) => (sound === 'tick' ? 'tock' : 'tick'));}, 1000);return () =>clearInterval (interval );});
derivedpermalink
导出片段: svelte/store#derived
从一个或多个其他存储派生出一个存储。 回调最初在第一个订阅者订阅时运行,然后在存储依赖发生更改时运行。
英Derives a store from one or more other stores. The callback runs initially when the first subscriber subscribes and then whenever the store dependencies change.
在最简单的版本中,derived
采用单个存储,回调返回派生值。
英In the simplest version, derived
takes a single store, and the callback returns a derived value.
ts
import {derived } from 'svelte/store';constdoubled =derived (a , ($a ) =>$a * 2);
回调可以通过接受第二个参数 set
和可选的第三个参数 update
来异步设置值,并在适当时调用其中一个或两个参数。
英The callback can set a value asynchronously by accepting a second argument, set
, and an optional third argument, update
, calling either or both of them when appropriate.
在这种情况下,你还可以将第三个参数传递给 derived
— 首次调用 set
或 update
之前派生存储的初始值。 如果没有指定初始值,则存储的初始值为 undefined
。
英In this case, you can also pass a third argument to derived
— the initial value of the derived store before set
or update
is first called. If no initial value is specified, the store's initial value will be undefined
.
ts
import {derived } from 'svelte/store';constdelayed =derived (a ,($a ,set ) => {setTimeout (() =>set ($a ), 1000);},2000);constdelayedIncrement =derived (a , ($a ,set ,update ) => {set ($a );setTimeout (() =>update ((x ) =>x + 1), 1000);// every time $a produces a value, this produces two// values, $a immediately and then $a + 1 a second later});
如果你从回调返回一个函数,则当 a) 回调再次运行,或 b) 最后一个订阅者取消订阅时,将会调用该函数。
英If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
ts
import {derived } from 'svelte/store';consttick =derived (frequency ,($frequency ,set ) => {constinterval =setInterval (() => {set (Date .now ());}, 1000 /$frequency );return () => {clearInterval (interval );};},2000);
在这两种情况下,参数数组都可以作为第一个参数传递,而不是单个存储。
英In both cases, an array of arguments can be passed as the first argument instead of a single store.
ts
import {derived } from 'svelte/store';constsummed =derived ([a ,b ], ([$a ,$b ]) =>$a +$b );constdelayed =derived ([a ,b ], ([$a ,$b ],set ) => {setTimeout (() =>set ($a +$b ), 1000);});
readonlypermalink
导出片段: svelte/store#readonly
这个简单的辅助函数使存储变为只读。 你仍然可以使用这个新的可读存储来订阅对原始版本的更改。
英This simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.
ts
import {readonly ,writable } from 'svelte/store';constwritableStore =writable (1);constreadableStore =readonly (writableStore );Property 'set' does not exist on type 'Readable<number>'.2339Property 'set' does not exist on type 'Readable<number>'.readableStore .subscribe (console .log );writableStore .set (2); // console: 2readableStore .set (2); // ERROR
getpermalink
导出片段: svelte/store#get
一般来说,你应该通过订阅存储并使用该值随时间的变化来读取该存储的值。 有时,你可能需要检索你未订阅的存储的值。 get
允许你这样做。
英Generally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get
allows you to do so.
这是通过创建订阅、读取值,然后取消订阅来实现的。 因此,不建议在热代码路径中使用它。
ts
import {get } from 'svelte/store';constvalue =get (store );
类型(Types)permalink
类型: svelte/store