Skip to main content

svelte/reactivity

Svelte 提供了各种内置函数的响应式版本,如 SvelteMapSvelteSetSvelteURL。这些可以从 svelte/reactivity 导入并像它们的原生对应项一样使用。

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- 对这些的更改... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- 将会更新 `href` 并反之亦然 -->
<input bind:value={url.href} />
import {
	class MediaQuery

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully — during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

&#x3C;script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
&#x3C;/script>

&#x3C;h1>{large.current ? 'large screen' : 'small screen'}&#x3C;/h1>
@extendsReactiveValue<boolean> *
@since5.7.0
MediaQuery
,
class SvelteDateSvelteDate, class SvelteMap<K, V>SvelteMap, class SvelteSet<T>SvelteSet, class SvelteURLSvelteURL, class SvelteURLSearchParamsSvelteURLSearchParams, function createSubscriber(start: (update: () => void) => (() => void) | void): () => void

Returns a subscribe function that, if called in an effect (including expressions in the template), calls its start callback with an update function. Whenever update is called, the effect re-runs.

If start returns a function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It’s best understood with an example. Here’s an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
@since5.7.0
createSubscriber
} from 'svelte/reactivity';

MediaQuery

自 5.7.0 版本可用

创建一个媒体查询并提供一个 current 属性,用于反映其是否匹配。

请谨慎使用 — 在服务端渲染期间,无法知道正确的值应该是什么,这可能导致内容在水合时发生变化。如果可以使用CSS中的媒体查询来达到相同效果,请使用CSS方式。

<script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
</script>

<h1>{large.current ? '大屏幕' : '小屏幕'}</h1>
class MediaQuery extends ReactiveValue<boolean> {}
constructor(query: string, fallback?: boolean | undefined);
  • query 媒体查询字符串
  • fallback 服务器的回退值

SvelteDate

class SvelteDate extends Date {}
constructor(...params: any[]);
#private;

SvelteMap

class SvelteMap<K, V> extends Map<K, V> {}
constructor(value?: Iterable<readonly [K, V]> | null | undefined);
set(key: K, value: V): this;
#private;

SvelteSet

class SvelteSet<T> extends Set<T> {}
constructor(value?: Iterable<T> | null | undefined);
add(value: T): this;
#private;

SvelteURL

class SvelteURL extends URL {}
get searchParams(): SvelteURLSearchParams;
#private;

SvelteURLSearchParams

class SvelteURLSearchParams extends URLSearchParams {}
[REPLACE](params: URLSearchParams): void;
#private;

createSubscriber

自 5.7.0 版本可用

返回一个 subscribe 函数,当在 effect 中调用时(包括模板中的表达式),会用一个 update 函数调用其 start 回调。每当调用 update 时,effect 会重新运行。

如果 start 返回一个函数,它将在 effect 销毁时被调用。

如果在多个 effect 中调用 subscribe,只要 effect 处于活动状态,start 只会被调用一次,并且返回的清理函数只会在所有 effect 都被销毁时才会被调用。

通过示例最容易理解。这是 MediaQuery 的一个实现:

import { function createSubscriber(start: (update: () => void) => (() => void) | void): () => void

Returns a subscribe function that, if called in an effect (including expressions in the template), calls its start callback with an update function. Whenever update is called, the effect re-runs.

If start returns a function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It’s best understood with an example. Here’s an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
@since5.7.0
createSubscriber
} from 'svelte/reactivity';
import { function on<Type extends keyof WindowEventMap>(window: Window, type: Type, handler: (this: Window, event: WindowEventMap[Type]) => any, options?: AddEventListenerOptions | undefined): () => void (+4 overloads)

Attaches an event handler to the window and returns a function that removes the handler. Using this rather than addEventListener will preserve the correct order relative to handlers added declaratively (with attributes like onclick), which use event delegation for performance reasons

on
} from 'svelte/events';
export class class MediaQueryMediaQuery { #query; #subscribe; constructor(query: anyquery) { this.#query = var window: Window & typeof globalThiswindow.function matchMedia(query: string): MediaQueryListmatchMedia(`(${query: anyquery})`); this.#subscribe = function createSubscriber(start: (update: () => void) => (() => void) | void): () => void

Returns a subscribe function that, if called in an effect (including expressions in the template), calls its start callback with an update function. Whenever update is called, the effect re-runs.

If start returns a function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It’s best understood with an example. Here’s an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
@since5.7.0
createSubscriber
((update: () => voidupdate) => {
// 当 `change` 事件发生时,重新运行任何读取 `this.current` 的 effect const const off: () => voidoff = on<MediaQueryList, "change">(element: MediaQueryList, type: "change", handler: (this: MediaQueryList, event: MediaQueryListEvent) => any, options?: AddEventListenerOptions | undefined): () => void (+4 overloads)

Attaches an event handler to an element and returns a function that removes the handler. Using this rather than addEventListener will preserve the correct order relative to handlers added declaratively (with attributes like onclick), which use event delegation for performance reasons

on
(this.#query, 'change', update: () => voidupdate);
// 当所有 effect 都被销毁时停止监听 return () => const off: () => voidoff(); }); } get MediaQuery.current: booleancurrent() { this.#subscribe(); // 返回查询的当前状态,无论我们是否在 effect 中 return this.#query.MediaQueryList.matches: booleanmatches; } }
function createSubscriber(
	start: (update: () => void) => (() => void) | void
): () => void;

在 GitHub 编辑此页面