Skip to main content

Stores

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

每当您引用 store 时,您都可以在组件内通过添加 $ 前缀访问它的值。这会导致 Svelte 声明带前缀的变量,在组件初始化时订阅 store,并在适当的时候取消订阅。

$ 前缀变量进行赋值要求该变量是一个可写的 store ,并将导致对 store 的 .set 方法的调用。

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

局部变量(不是 store 的值)不能$ 前缀。

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

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

	count.set(1);
	console.log($count); // 输出 1

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

何时使用 store

在 Svelte 5 之前, store 是创建跨组件响应式状态或提取逻辑的首选解决方案。随着符文的出现,这些用例已大大减少。

  • 在提取逻辑时,最好利用符文的通用响应性:你可以在组件顶层之外使用符文,甚至可以将它们放入 JavaScript 或 TypeScript 文件(使用 .svelte.js.svelte.ts 文件后缀)。
  • 在创建共享状态时,你可以创建一个包含所需值的 $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>用户名: {userState.name}</p>
<button onclick={() => {
	userState.name = '新名字';
}}>
	修改名字
</button>
<script lang="ts">
	import { userState } from './state.svelte.js';
</script>

<p>用户名: {userState.name}</p>
<button onclick={() => {
	userState.name = '新名字';
}}>
	修改名字
</button>

当你有复杂的异步数据流,或需要手动控制更新值或监听变化时, store 仍然是一个不错的解决方案。如果你熟悉 RxJs 并希望复用这些知识,$ 也会对你很有帮助。

svelte/store

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

writable

一个函数,可以创建一个从“外部”组件设置值的 store。store 是一个额外带有 setupdate 方法的对象。

set 是一个方法,它接受一个参数,该参数是要设置的值。如果 store 值与参数值不相等,则 store 值将设置为参数值。

update 是一个方法,它接受一个参数,该参数是一个回调函数。回调函数以现有的 store 值作为其参数,并返回要设置到 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);
}); // 输出 '0' const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // 输出 '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); // 输出 '2'

如果 writeable 的第二个参数传递了一个函数,它将在订阅者数量从 0 到 1 时被调用(而不是从 1 到 2,等等)。

该函数将接收一个 set 函数,用于改变 store 的值,以及一个 update 函数,其工作原理类似于 store 的 update 方法,接受一个回调函数,根据旧值计算 store 的新值。它必须返回一个 stop 函数,当订阅者数量从 1 到 0 时调用该函数。

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
('得到一个订阅者');
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
('没有更多的订阅者');
}); const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // 不执行
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);
}); // 输出 '得到一个订阅者',然后输出 '1' const unsubscribe: () => voidunsubscribe(); // 输出 '没有更多的订阅者'

注意,当 writable 的值被销毁时,例如当页面刷新时,其值会丢失。但是,你可以编写自己的逻辑,将值同步到比如 localStorage 中。

readable

创建一个不能从“外部”设置值的 store ,第一个参数是 store 的初始值,第二个参数与 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

从一个或多个其他 store 派生出一个 store 。回调在第一个订阅者订阅时运行,然后在 store 依赖关系发生变化时运行。

在最简单的版本中,derived 接受一个 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 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 异步设置一个值,并在适当时调用它们中的一个或两个。

在这种情况下,您还可以向 derived 传递第三个参数 —— 派生 store 在第一次调用 setupdate 之前的初始值。如果未指定初始值,则 store 的初始值为 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);
// 每次 $a 产生一个值时,这个也会产生两个值 // $a 立即输出然后 $a + 1 一秒后输出 });

如果你从回调中返回一个函数,它将在以下情况被调用:

  1. 回调再次运行的时候
  2. 最后一个订阅者取消订阅的时候
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 );

在这两种情况下,可以将一个参数数组作为第一个参数传递,而不是单个 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

这个简单的辅助函数使得 store 只读。你仍然可以使用这个新的可读 store 订阅原始 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

通常,你应该通过订阅 store 并随着时间变化使用其值来读取 store 的值。偶尔,你可能需要检索未订阅的 store 的值。get 允许你这样做。

这样做背后是通过创建一个订阅、读取值、再然后取消订阅来实现的。因此,不建议在频繁使用的代码路径中使用。

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 合约

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

你可以通过实现 store 合约(store contract) 创建自己的 store ,而不依赖于 svelte/store

  1. store 必须包含一个 .subscribe 方法,该方法必须接受一个订阅函数作为参数。此订阅函数必须在调用 .subscribe 时立即和同步地传入 store 的当前值进行调用。无论何时 store 的值发生变化,所有激活的订阅函数都必须被同步调用。
  2. .subscribe 方法必须返回一个取消订阅函数。调用取消订阅函数必须停止其订阅,并且 store 不得再次调用其相应的订阅函数。
  3. 一个 store 可以 可选的 包含一个 .set 方法,该方法必须接受一个新的 store 值作为参数,并同步调用 store 所有激活的订阅函数。这样的 store 称为 可写的 store(writable store)

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

在 GitHub 编辑此页面