Skip to main content

存储

存储是一个对象,允许通过简单的存储合约对值进行反应式访问。svelte/store 模块 包含满足此合同的最小存储实现。

¥A store is an object that allows reactive access to a value via a simple store contract. The svelte/store module contains minimal store implementations which fulfil this contract.

任何时候你有对存储的引用,你都可以通过在组件中加上 $ 字符来访问其值。这会导致 Svelte 声明前缀变量,在组件初始化时订阅存储并在适当的时候取消订阅。

¥Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialisation and unsubscribe when appropriate.

$ 前缀变量的赋值要求变量是可写存储,并将导致调用存储的 .set 方法。

¥Assignments to $-prefixed variables require that the variable be a writable store, and will result in a call to the store’s .set method.

请注意,必须在组件的顶层声明存储 — 例如,不能在 if 块或函数内。

¥Note that the store must be declared at the top level of the component — not inside an if block or a function, for example.

本地变量(不代表存储值)不能有 $ 前缀。

¥Local variables (that do not represent store values) must not have a $ prefix.

<script>
	import { writable } from 'svelte/store';

	const count = writable(0);
	console.log($count); // logs 0

	count.set(1);
	console.log($count); // logs 1

	$count = 2;
	console.log($count); // logs 2
</script>

何时使用存储(When to use stores)

¥When to use stores

在 Svelte 5 之前,存储是创建跨组件反应状态或提取逻辑的首选解决方案。使用 runes,这些用例大大减少。

¥Prior to Svelte 5, stores were the go-to solution for creating cross-component reactive states or extracting logic. With runes, these use cases have greatly diminished.

  • 提取逻辑时,最好利用符文的通用反应性:你可以在组件顶层之外使用符文,甚至可以将它们放入 JavaScript 或 TypeScript 文件中(使用 .svelte.js.svelte.ts 文件结尾)

    ¥when extracting logic, it’s better to take advantage of runes’ universal reactivity: You can use runes outside the top level of components and even place them into JavaScript or TypeScript files (using a .svelte.js or .svelte.ts file ending)

  • 创建共享状态时,你可以创建一个包含所需值的 $state 对象,然后操作该状态

    ¥when creating shared state, you can create a $state object containing the values you need and then manipulate said state

state.svelte
export const 
const userState: {
    name: string;
}
userState
=
function $state<{
    name: string;
}>(initial: {
    name: string;
}): {
    name: string;
} (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);

https://svelte.dev/docs/svelte/$state

@paraminitial The initial value
$state
({
name: stringname: 'name', /* ... */ });
App
<script>
	import { userState } from './state.svelte.js';
</script>

<p>User name: {userState.name}</p>
<button onclick={() => {
	userState.name = 'new name';
}}>
	change name
</button>
<script lang="ts">
	import { userState } from './state.svelte.js';
</script>

<p>User name: {userState.name}</p>
<button onclick={() => {
	userState.name = 'new name';
}}>
	change name
</button>

当你拥有复杂的异步数据流,或者需要对更新值或监听更改进行更多手动控制时,存储仍然是一个很好的解决方案。如果你熟悉 RxJs 并希望重复使用这些知识,$ 对你来说也很有用。

¥Stores are still a good solution when you have complex asynchronous data streams or it’s important to have more manual control over updating values or listening to changes. If you’re familiar with RxJs and want to reuse that knowledge, the $ also comes in handy for you.

svelte/store

svelte/store 模块包含一个最小的存储实现,可满足存储合同。它提供了创建可以从外部更新的存储的方法、只能从内部更新的存储的方法以及组合和派生存储的方法。

¥The svelte/store module contains a minimal store implementation which fulfil the store contract. It provides methods for creating stores that you can update from the outside, stores you can only update from the inside, and for combining and deriving stores.

writable

创建一个存储的函数,该存储具有可以从 ‘outside’ 组件设置的值。它被创建为具有附加 setupdate 方法的对象。

¥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.

store
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const count: Writable<number>count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(0);
const count: Writable<number>count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
((value: numbervalue) => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(value: numbervalue);
}); // logs '0' const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // logs '1'
const count: Writable<number>count.Writable<number>.update(this: void, updater: Updater<number>): void

Update value using callback and inform subscribers.

@paramupdater callback
update
((n: numbern) => n: numbern + 1); // logs '2'

如果将函数作为第二个参数传递,则当订阅者数量从零到一(但不是从一到二等)时将调用该函数。该函数将传递一个更改存储值的 set 函数和一个像存储上的 update 方法一样工作的 update 函数,它采用回调来根据旧值计算存储的新值。它必须返回一个 stop 函数,当订阅者数量从一变为零时调用该函数。

¥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.

store
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const count: Writable<number>count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(0, () => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('got a subscriber');
return () => var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('no more subscribers');
}); const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // does nothing
const const unsubscribe: Unsubscriberunsubscribe = const count: Writable<number>count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
((value: numbervalue) => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(value: numbervalue);
}); // logs 'got a subscriber', then '1' const unsubscribe: () => voidunsubscribe(); // 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.

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.

import { function readable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Readable<T>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
} from 'svelte/store';
const const time: Readable<Date>time = readable<Date>(value?: Date | undefined, start?: StartStopNotifier<Date> | undefined): Readable<Date>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
(), (set: (value: Date) => voidset) => {
set: (value: Date) => voidset(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
());
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
set: (value: Date) => voidset(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
());
}, 1000); return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
}); const const ticktock: Readable<string>ticktock = readable<string>(value?: string | undefined, start?: StartStopNotifier<string> | undefined): Readable<string>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
('tick', (set: (value: string) => voidset, update: (fn: Updater<string>) => voidupdate) => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
update: (fn: Updater<string>) => voidupdate((sound: stringsound) => (sound: stringsound === 'tick' ? 'tock' : 'tick')); }, 1000); return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
});

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.

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const doubled: Readable<number>doubled = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number) => number, initial_value?: number | undefined): Readable<number> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(const a: Writable<number>a, ($a: number$a) => $a: number$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 - 在首次调用 setupdate 之前派生存储的初始值。如果未指定初始值,则存储的初始值将为 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.

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const delayed: Readable<number>delayed = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(
const a: Writable<number>a, ($a: number$a, set: (value: number) => voidset) => { function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => set: (value: number) => voidset($a: number$a), 1000);
}, 2000 ); const const delayedIncrement: Readable<unknown>delayedIncrement = derived<Writable<number>, unknown>(stores: Writable<number>, fn: (values: number, set: (value: unknown) => void, update: (fn: Updater<unknown>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(const a: Writable<number>a, ($a: number$a, set: (value: unknown) => voidset, update: (fn: Updater<unknown>) => voidupdate) => {
set: (value: unknown) => voidset($a: number$a); function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => update: (fn: Updater<unknown>) => voidupdate((x: unknownx) => 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.

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const tick: Readable<number>tick = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(
const frequency: Writable<number>frequency, ($frequency: number$frequency, set: (value: number) => voidset) => { const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
set: (value: number) => voidset(var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
.DateConstructor.now(): number

Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).

now
());
}, 1000 / $frequency: number$frequency); return () => { function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
}; }, 2000 );

在这两种情况下,参数数组都可以作为第一个参数传递,而不是单个存储。

¥In both cases, an array of arguments can be passed as the first argument instead of a single store.

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const summed: Readable<number>summed = derived<[Writable<number>, Writable<number>], number>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number]) => number, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
([const a: Writable<number>a, const b: Writable<number>b], ([$a: number$a, $b: number$b]) => $a: number$a + $b: number$b);
const const delayed: Readable<unknown>delayed = derived<[Writable<number>, Writable<number>], unknown>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number], set: (value: unknown) => void, update: (fn: Updater<...>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
([const a: Writable<number>a, const b: Writable<number>b], ([$a: number$a, $b: number$b], set: (value: unknown) => voidset) => {
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => set: (value: unknown) => voidset($a: number$a + $b: number$b), 1000);
});

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.

import { function readonly<T>(store: Readable<T>): Readable<T>

Takes a store and returns a new one derived from the old one that is readable.

@paramstore - store to make readonly
readonly
, function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const writableStore: Writable<number>writableStore = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(1);
const const readableStore: Readable<number>readableStore = readonly<number>(store: Readable<number>): Readable<number>

Takes a store and returns a new one derived from the old one that is readable.

@paramstore - store to make readonly
readonly
(const writableStore: Writable<number>writableStore);
const readableStore: Readable<number>readableStore.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
(var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(...data: any[]): void (+1 overload)log);
const writableStore: Writable<number>writableStore.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(2); // console: 2
const readableStore: Readable<number>readableStore.set(2); // ERROR

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.

这通过创建订阅、读取值然后取消订阅来实现。因此,不建议在热代码路径中使用它。

¥[!NOTE] This works by creating a subscription, reading the value, then unsubscribing. It’s therefore not recommended in hot code paths.

import { function get<T>(store: Readable<T>): T

Get the current value from a store by subscribing and immediately unsubscribing.

get
} from 'svelte/store';
const const value: stringvalue = get<string>(store: Readable<string>): string

Get the current value from a store by subscribing and immediately unsubscribing.

get
(const store: Writable<string>store);

存储合同(Store contract)

¥Store contract

store = { subscribe: (subscription: (value: any) => void) => () => undefinedsubscribe: (subscription: (value: any) => voidsubscription: (value: anyvalue: any) => void) => (() => void), set: (value: any) => undefinedset?: (value: anyvalue: any) => void }

你可以通过实现存储合同来创建自己的存储而不依赖 svelte/store

¥You can create your own stores without relying on svelte/store, by implementing the store contract:

  1. 存储必须包含 .subscribe 方法,该方法必须接受订阅功能作为其参数。在调用 .subscribe 时,必须立即使用存储的当前值同步调用此订阅函数。每当存储的值发生变化时,以后都必须同步调用存储的所有活动订阅函数。

    ¥A store must contain a .subscribe method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store’s current value upon calling .subscribe. All of a store’s active subscription functions must later be synchronously called whenever the store’s value changes.

  2. .subscribe 方法必须返回取消订阅函数。调用取消订阅函数必须停止其订阅,并且其对应的订阅函数不得被存储再次调用。

    ¥The .subscribe method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.

  3. 存储可以选择包含 .set 方法,该方法必须接受存储的新值作为其参数,并同步调用存储的所有活动订阅功能。这样的存储称为可写存储。

    ¥A store may optionally contain a .set method, which must accept as its argument a new value for the store, and which synchronously calls all of the store’s active subscription functions. Such a store is called a writable store.

为了与 RxJS Observables 互操作,.subscribe 方法也可以返回具有 .unsubscribe 方法的对象,而不是直接返回取消订阅函数。但请注意,除非 .subscribe 同步调用订阅(Observable 规范不要求这样做),否则 Svelte 将把存储的值视为 undefined,直到它这样做为止。

¥For interoperability with RxJS Observables, the .subscribe method is also allowed to return an object with an .unsubscribe method, rather than return the unsubscription function directly. Note however that unless .subscribe synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as undefined until it does.

上一页 下一页