商店
商店是一个对象,它允许通过简单的商店契约以响应方式访问值。该svelte/store
模块包含满足此契约的最小商店实现。
任何时候你拥有商店的引用,你都可以在组件内部通过在它前面加上$
字符来访问它的值。这会导致 Svelte 声明带前缀的变量,在组件初始化时订阅商店,并在适当的时候取消订阅。
对带$
前缀的变量的赋值要求该变量是可写商店,并且会导致调用商店的.set
方法。
请注意,商店必须在组件的顶层声明 - 例如,不要在if
块或函数内部声明。
局部变量(不表示商店值)不能带有$
前缀。
<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>
何时使用商店
在 Svelte 5 之前,商店是创建跨组件响应式状态或提取逻辑的首选解决方案。使用符文,这些用例已大大减少。
- 在提取逻辑时,最好利用符文的通用响应性:你可以在组件的顶层之外使用符文,甚至将它们放入 JavaScript 或 TypeScript 文件中(使用
.svelte.js
或.svelte.ts
文件结尾) - 在创建共享状态时,你可以创建一个包含所需值的
$state
对象,然后操作该状态
export const const userState: {
name: string;
}
userState = function $state<{
name: string;
}>(initial: {
name: string;
}): {
name: string;
} (+1 overload)
namespace $state
$state({
name: string
name: 'name',
/* ... */
});
<script>
import { userState } from './state.svelte';
</script>
<p>User name: {userState.name}</p>
<button onclick={() => {
userState.name = 'new name';
}}>
change name
</button>
当你拥有复杂异步数据流或需要更手动地控制更新值或侦听更改时,商店仍然是一个不错的解决方案。如果你熟悉 RxJs 并希望重用该知识,$
对你也很有用。
svelte/store
该svelte/store
模块包含一个满足商店契约的最小商店实现。它提供了创建商店的方法,你可以从外部更新这些商店,只能从内部更新的商店,以及组合和派生商店。
writable
创建商店的函数,该商店具有可以从“外部”组件设置的值。它被创建为一个对象,并带有额外的set
和update
方法。
set
是一个接受一个参数的方法,该参数是要设置的值。如果商店值尚不等于它,则商店值将设置为参数的值。
update
是一个接受一个参数的方法,该参数是一个回调。回调以现有商店值作为其参数,并返回要设置为商店的新值。
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.
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.
writable(0);
const count: Writable<number>
count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber
Subscribe on value changes.
subscribe((value: number
value) => {
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
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.
log(value: number
value);
}); // logs '0'
const count: Writable<number>
count.Writable<number>.set(this: void, value: number): void
Set value and inform subscribers.
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.
update((n: number
n) => n: number
n + 1); // logs '2'
如果将函数作为第二个参数传递,则当订阅者数量从零变为一(但不是从一变为二等)时,将调用该函数。该函数将传递一个set
函数,该函数更改商店的值,以及一个update
函数,该函数的工作方式类似于商店上的update
方法,它接受一个回调以根据商店的旧值计算商店的新值。它必须返回一个stop
函数,该函数在订阅者数量从一变为零时调用。
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.
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.
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
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.
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
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.
log('no more subscribers');
});
const count: Writable<number>
count.Writable<number>.set(this: void, value: number): void
Set value and inform subscribers.
set(1); // does nothing
const const unsubscribe: Unsubscriber
unsubscribe = const count: Writable<number>
count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber
Subscribe on value changes.
subscribe((value: number
value) => {
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
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.
log(value: number
value);
}); // logs 'got a subscriber', then '1'
const unsubscribe: () => void
unsubscribe(); // logs 'no more subscribers'
请注意,当writable
被销毁时,例如当页面刷新时,它的值会丢失。但是,你可以编写自己的逻辑将值同步到例如localStorage
。
readable
创建一个其值不能从“外部”设置的商店,第一个参数是商店的初始值,readable
的第二个参数与writable
的第二个参数相同。
import { function readable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Readable<T>
Creates a Readable
store that allows reading by subscription.
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.
readable(new var Date: DateConstructor
new () => Date (+4 overloads)
Date(), (set: (value: Date) => void
set) => {
set: (value: Date) => void
set(new var Date: DateConstructor
new () => Date (+4 overloads)
Date());
const const interval: NodeJS.Timeout
interval = 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()
.
setInterval(() => {
set: (value: Date) => void
set(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()
.
clearInterval(const interval: NodeJS.Timeout
interval);
});
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.
readable('tick', (set: (value: string) => void
set, update: (fn: Updater<string>) => void
update) => {
const const interval: NodeJS.Timeout
interval = 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()
.
setInterval(() => {
update: (fn: Updater<string>) => void
update((sound: string
sound) => (sound: string
sound === 'tick' ? 'tock' : 'tick'));
}, 1000);
return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)
Cancels a Timeout
object created by setInterval()
.
clearInterval(const interval: NodeJS.Timeout
interval);
});
derived
从一个或多个其他商店派生一个商店。回调在第一个订阅者订阅时最初运行,然后在商店依赖项发生更改时运行。
在最简单的版本中,derived
接受一个商店,并且回调返回一个派生值。
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
- 在第一次调用set
或update
之前派生商店的初始值。如果未指定初始值,则商店的初始值将为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) => void
set) => {
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()
.
setTimeout(() => set: (value: number) => void
set($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) => void
set, update: (fn: Updater<unknown>) => void
update) => {
set: (value: unknown) => void
set($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()
.
setTimeout(() => update: (fn: Updater<unknown>) => void
update((x: unknown
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) 最后一个订阅者取消订阅。
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) => void
set) => {
const const interval: NodeJS.Timeout
interval = 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()
.
setInterval(() => {
set: (value: number) => void
set(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()
.
clearInterval(const interval: NodeJS.Timeout
interval);
};
},
2000
);
在这两种情况下,都可以将参数数组作为第一个参数传递,而不是单个商店。
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) => void
set) => {
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()
.
setTimeout(() => set: (value: unknown) => void
set($a: number
$a + $b: number
$b), 1000);
});
readonly
这个简单的辅助函数使商店只读。你仍然可以使用这个新的可读商店订阅原始商店的变化。
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.
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.
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.
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.
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.
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
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.
set(2); // console: 2
const readableStore: Readable<number>
readableStore.set(2); // ERROR
get
通常,你应该通过订阅商店并使用其随时间变化的值来读取商店的值。偶尔,你可能需要检索你未订阅的商店的值。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: string
value = 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 = { subscribe: (subscription: (value: any) => void) => () => undefined
subscribe: (subscription: (value: any) => void
subscription: (value: any
value: any) => void) => (() => void), set: (value: any) => undefined
set?: (value: any
value: any) => void }
你可以创建自己的商店,而无需依赖svelte/store
,方法是实现商店契约
- 商店必须包含一个
.subscribe
方法,该方法必须接受订阅函数作为其参数。在调用.subscribe
时,此订阅函数必须立即且同步地被调用,并使用商店的当前值。商店的所有活动订阅函数都必须在商店的值发生更改时稍后同步调用。 .subscribe
方法必须返回一个取消订阅函数。调用取消订阅函数必须停止其订阅,并且其相应的订阅函数不得再次被商店调用。- 商店可以可选地包含一个
.set
方法,该方法必须接受商店的新值作为其参数,并且同步调用商店的所有活动订阅函数。这样的商店称为可写商店。
为了与 RxJS Observables 互操作,.subscribe
方法也允许返回一个包含.unsubscribe
方法的对象,而不是直接返回取消订阅函数。但是请注意,除非.subscribe
同步调用订阅(Observable 规范不要求这样做),否则 Svelte 会将商店的值视为undefined
,直到它这样做。