Svelte fournit des versions réactives de différentes classes natives comme
Map,
Set et
URL, qui peuvent être utilisées exactement
comme leur version native, ainsi qu’un certain nombre d’utilitaires permettant de bien gérer la
réactivité.
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.
A reactive version of the built-in Date object.
Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat)
in an effect or derived
will cause it to be re-evaluated when the value of the date changes.
<script>import{SvelteDate}from'svelte/reactivity';constdate=newSvelteDate();constformatter=newIntl.DateTimeFormat(undefined,{hour:'numeric',minute:'numeric',second:'numeric'});$effect(()=>{constinterval=setInterval(()=>{date.setTime(Date.now());},1000);return()=>{clearInterval(interval);};});</script><p>The time is {formatter.format(date)}</p>
A reactive version of the built-in Map object.
Reading contents of the map (by iterating, or by reading map.size or calling map.get(...) or map.has(...) as in the tic-tac-toe example below) in an effect or derived
will cause it to be re-evaluated as necessary when the map is updated.
Note that values in a reactive map are not made deeply reactive.
<script>import{SvelteMap}from'svelte/reactivity';import{result}from'./game.js';letboard=newSvelteMap();letplayer=$state('x');letwinner=$derived(result(board));functionreset(){player='x';board.clear();}</script><divclass="board">{#eachArray(9),i}<buttondisabled={board.has(i)||winner}onclick={()=>{board.set(i,player);player=player==='x'?'o':'x';}}>{board.get(i)}</button>{/each}</div>{#ifwinner}<p>{winner} wins!</p><buttononclick={reset}>reset</button>{:else}<p>{player} is next</p>{/if}
A reactive version of the built-in Set object.
Reading contents of the set (by iterating, or by reading set.size or calling set.has(...) as in the example below) in an effect or derived
will cause it to be re-evaluated as necessary when the set is updated.
Note that values in a reactive set are not made deeply reactive.
<script>import{SvelteSet}from'svelte/reactivity';letmonkeys=newSvelteSet();functiontoggle(monkey){if(monkeys.has(monkey)){monkeys.delete(monkey);}else{monkeys.add(monkey);}}</script>{#each['🙈', '🙉', '🙊'] as monkey}<buttononclick={()=>toggle(monkey)}>{monkey}</button>{/each}<buttononclick={()=>monkeys.clear()}>clear</button>{#ifmonkeys.has('🙈')}<p>see no evil</p>{/if}{#ifmonkeys.has('🙉')}<p>hear no evil</p>{/if}{#ifmonkeys.has('🙊')}<p>speak no evil</p>{/if}
A reactive version of the built-in URL object.
Reading properties of the URL (such as url.href or url.pathname) in an effect or derived
will cause it to be re-evaluated as necessary when the URL changes.
<script>import{SvelteURL}from'svelte/reactivity';consturl=newSvelteURL('https://example.com/path');</script><!-- changes to these... --><inputbind:value={url.protocol}/><inputbind:value={url.hostname}/><inputbind:value={url.pathname}/><hr/><!-- will update `href` and vice versa --><inputbind:value={url.href}size="65"/>
A reactive version of the built-in URLSearchParams object.
Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived
will cause it to be re-evaluated as necessary when the params are updated.
Returns a subscribe function that integrates external event-based systems with Svelte's reactivity.
It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.
If subscribe is called inside an effect (including indirectly, for example inside a getter),
the start callback will be called with an update function. Whenever update is called, the effect re-runs.
If start returns a cleanup 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';exportclassMediaQuery{ #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`constoff=on(this.#query,'change',update);// stop listening when all the effects are destroyedreturn()=>off();});}getcurrent(){// This makes the getter reactive, if read in an effectthis.#subscribe();// Return the current state of the query, whether or not we're in an effectreturnthis.#query.matches;}}
Crée une media query et fournit une propriété current qui reflète si oui ou non celle-ci
correspond.
Servez-vous en avec précaution — pendant le rendu côté serveur, il n’y a aucun moyen de connaître la
valeur correcte, causant potentiellement des problèmes de contenu lors de l’hydratation.
Si vous pouvez utiliser une media query en CSS pour obtenir le même résultat, faites-le.
Une version réactive de l’objet natif
Date. Lire
une SvelteDate (que ce soit via des méthodes comme date.getTime() ou date.toString(), ou via
des choses comme
Intl.DateTimeFormat)
dans un effet ou un dérivé va déclencher sa
ré-évaluation lorsque la valeur de la date change.
<script>import{SvelteDate}from'svelte/reactivity';constdate=newSvelteDate();constformatter=newIntl.DateTimeFormat(undefined,{hour:'numeric',minute:'numeric',second:'numeric'});$effect(()=>{constinterval=setInterval(()=>{date.setTime(Date.now());},1000);return()=>{clearInterval(interval);};});</script><p>The time is {formatter.format(date)}</p>
classSvelteDateextendsDate{/*…*/}
constructor(...params:any[]);
SvelteMap
Une version réactive de l’objet natif
Map.
Lire le contenu d’une SvelteMap (en itérant, ou en lisant map.size, ou en utilisant
map.get(...). ou map.has(...) comme dans l’exemple de
morpion ci-dessous) dans un
effet ou un dérivé va déclencher sa ré-évaluation
si nécessaire lors de la mise à jour de la map.
Notez que les valeurs au sein d’une map réactive ne sont pas rendues profondément
réactives.
<script>import{SvelteMap}from'svelte/reactivity';import{result}from'./game.js';letboard=newSvelteMap();letplayer=$state('x');letwinner=$derived(result(board));functionreset(){player='x';board.clear();}</script><divclass="board">{#eachArray(9),i}<buttondisabled={board.has(i)||winner}onclick={()=>{board.set(i,player);player=player==='x'?'o':'x';}}>{board.get(i)}</button>{/each}</div>{#ifwinner}<p>{winner} gagne !</p><buttononclick={reset}>recommencer</button>{:else}<p>C'est le tour de {player}</p>{/if}
Une version réactive de l’objet natif
Set.
Lire le contenu d’un SvelteSet (en itérant, ou en lisant set.size, ou en utilisant
set.has(...) comme dans l’exemple ci-dessous) dans un
effet ou un dérivé va déclencher sa ré-évaluation
si nécessaire lors de la mise à jour du set.
Notez que les valeurs au sein d’un map réactif ne sont pas rendues profondément
réactives.
<script>import{SvelteSet}from'svelte/reactivity';letmonkeys=newSvelteSet();functiontoggle(monkey){if(monkeys.has(monkey)){monkeys.delete(monkey);}else{monkeys.add(monkey);}}</script>{#each['🙈', '🙉', '🙊'] as monkey}<buttononclick={()=>toggle(monkey)}>{monkey}</button>{/each}<buttononclick={()=>monkeys.clear()}>effacer</button>{#ifmonkeys.has('🙈')}<p>ne pas voir le mal</p>{/if}{#ifmonkeys.has('🙉')}<p>ne pas entendre le mal</p>{/if}{#ifmonkeys.has('🙊')}<p>ne pas dire le mal</p>{/if}
classSvelteSet<T>extendsSet<T>{/*…*/}
constructor(value?:Iterable<T>|null|undefined);
add(value:T):this;
SvelteURL
Une version réactive de l’objet natif
URL. Lire des propriétés d’une SvelteURL
(comme url.href ou url.pathname) dans un effet ou un
dérivé va déclencher sa ré-évaluation si nécessaire lors de la mise à jour
de l’url.
<script>import{SvelteURL}from'svelte/reactivity';consturl=newSvelteURL('https://example.com/path');</script><!-- les changements produits ici... --><inputbind:value={url.protocol}/><inputbind:value={url.hostname}/><inputbind:value={url.pathname}/><hr/><!-- vont mettre à jour `url.href` et inversement --><inputbind:value={url.href}size="65"/>
classSvelteURLextendsURL{/*…*/}
getsearchParams():SvelteURLSearchParams;
SvelteURLSearchParams
Une version réactive de l’objet natif
URLSearchParams. Lire le contenu
d’un SvelteURLSearchParams (en itérant, ou en appelant params.get(...) ou params.getAll(...)
comme dans l’exemple ci-dessous) dans un
effet ou un dérivé va déclencher sa ré-évaluation
si nécessaire lors de la mise à jour des paramètres de recherche.
Renvoie une fonction subscribe qui intègre des systèmes externes basés sur des évènements dans la
réactivité de Svelte.
C’est particulièrement utile pour intégrer des APIs comme MediaQuery, IntersectionObserver, ou
WebSocket.
Si subscribe est appelée au sein d’un effet (y compris indirectement, par exemple dans un getter),
le callback start sera appelé avec une fonction update. À chaque fois que update est appelée,
l’effet est ré-exécuté.
Si start renvoie une fonction de nettoyage, elle sera exécutée lors de la destruction de l’effet.
Si subscribe est appelée dans plusieurs effets, start ne sera appelé qu’une seule fois tant que
les effets sont actifs, et la fonction de “destruction” renvoyée ne sera appelée que lorsque tous
les effets concernées seront détruits.
On comprend mieux cette fonctionnalité avec un exemple. Voici l’implémentation de
MediaQuery :
Returns a subscribe function that integrates external event-based systems with Svelte's reactivity.
It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.
If subscribe is called inside an effect (including indirectly, for example inside a getter),
the start callback will be called with an update function. Whenever update is called, the effect re-runs.
If start returns a cleanup 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';exportclassMediaQuery{ #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`constoff=on(this.#query,'change',update);// stop listening when all the effects are destroyedreturn()=>off();});}getcurrent(){// This makes the getter reactive, if read in an effectthis.#subscribe();// Return the current state of the query, whether or not we're in an effectreturnthis.#query.matches;}}
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
The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.
Returns a subscribe function that integrates external event-based systems with Svelte's reactivity.
It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.
If subscribe is called inside an effect (including indirectly, for example inside a getter),
the start callback will be called with an update function. Whenever update is called, the effect re-runs.
If start returns a cleanup 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';exportclassMediaQuery{ #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`constoff=on(this.#query,'change',update);// stop listening when all the effects are destroyedreturn()=>off();});}getcurrent(){// This makes the getter reactive, if read in an effectthis.#subscribe();// Return the current state of the query, whether or not we're in an effectreturnthis.#query.matches;}}
5.7.0
reference((update(parameter)update:()=>void)=>{// lorsque l'évènement `change` se produit, rejoue tout effet qui lit `this.current`constoffconstoff:()=>void=on(alias)on<MediaQueryList,"change">(element:MediaQueryList,type:"change",handler:(this:MediaQueryList,event:MediaQueryListEvent&{currentTarget:MediaQueryList;})=>any,options?:AddEventListenerOptions|undefined):()=>void(+4overloads)importon
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
reference(this.#query,'change',update(parameter)update:()=>void);// arrête d'écouter lorsque tous les effets sont détruitsreturn()=>offconstoff:()=>void();});}getcurrent(getter)MediaQuery.current:boolean(){ // This makes the getter reactive, if read in an effect
this.#subscribe();// renvoie l'état courant de la query, que l'on soit ou non dans un effetreturnthis.#query.matches(property)MediaQueryList.matches:boolean
The matches read-only property of the MediaQueryList interface is a boolean value that returns true if the document currently matches the media query list, or false if not.