儲存 (Stores)
儲存 (store) 是一個物件,它允許透過簡單的儲存合約反應式地存取值。 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
Declares reactive state.
Example:
let count = $state(0);
$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
,直到它執行此操作。