Bases de Svelte
Introduction
Liaisons
Classes et styles
Svelte avancé
Réutiliser du contenu
Mouvements
Liaisons avancées
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Les classes sont particulièrement utiles lorsque vous avez besoin de valider des données. Dans le
cas de cette classe Box
, il ne devrait pas être possible de faire grandir la taille au-delà du
maximum autorisé par les sliders, mais pourtant c’est bien ce qui se passe.
Nous pouvons corriger cela en remplaçant width
et height
avec des getters et setters, aussi
appelés accesseurs. D’abord, convertissez-les en propriétés
privées
:
class Box {
#width = $state(0);
#height = $state(0);
area = $derived(this.#width * this.#height);
constructor(width, height) {
this.#width = width;
this.#height = height;
}
// ...
}
Puis, créez des getters et setters :
class Box {
// ...
get width() {
return this.#width;
}
get height() {
return this.#height;
}
set width(value) {
this.#width = value;
}
set height(value) {
this.#height = value;
}
embiggen(amount) {
this.width += amount;
this.height += amount;
}
}
Enfin, ajoutez de la validation aux setters :
set width(value) {
this.#width = Math.max(0, Math.min(MAX_SIZE, value));
}
set height(value) {
this.#height = Math.max(0, Math.min(MAX_SIZE, value));
}
Il est maintenant impossible d’augmenter la taille de la boîte au-delà des limites raisonnables, que
ce soit via bind:value
des inputs, ou via la méthode embiggen
, peu importe l’insistance avec
laquelle vous appuyez sur le bouton.
Modifier cette page sur Github
<script>
const MAX_SIZE = 200;
class Box {
width = $state(0);
height = $state(0);
area = $derived(this.width * this.height);
constructor(width, height) {
this.width = width;
this.height = height;
}
embiggen(amount) {
this.width += amount;
this.height += amount;
}
}
const box = new Box(100, 100);
</script>
<label>
<input type="range" bind:value={box.width} min={0} max={MAX_SIZE} />
{box.width}
</label>
<label>
<input type="range" bind:value={box.height} min={0} max={MAX_SIZE} />
{box.height}
</label>
<button onclick={() => box.embiggen(10)}>agrandir</button>
<hr>
<div
class="box"
style:width="{box.width}px"
style:height="{box.height}px"
>
{box.area}
</div>
<style>
label {
display: flex;
align-items: center;
}
hr {
margin: 1em 0;
border: none;
border-bottom: 1px solid #888;
}
.box {
background: radial-gradient(at 25% 25%, hsl(15 100 60), hsl(15 100 50)) ;
border-radius: 2px;
filter: drop-shadow(0 0 10px hsl(15 100 50 / 0.3));
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
</style>