Reactive Statements
Desliza para mostrar el menú
Reactive variables allow the interface to update automatically when data changes. Reactive statements take this idea even further by allowing values to react to other values automatically.
This makes it easier to keep related data synchronized inside your application.
What Are Reactive Statements?
Reactive statements automatically run whenever the values they depend on change.
In Svelte, reactive statements use the $: syntax.
For example:
<script>
let price = 20;
let quantity = 3;
$: total = price * quantity;
</script>
<h1>Total: ${total}</h1>
Whenever price or quantity changes, the total value updates automatically.
Why Reactive Statements Are Useful
In many applications, some values depend on other pieces of data.
For example:
- Shopping cart totals;
- Filtered lists;
- Form validation;
- Calculated statistics;
- Dynamic UI labels.
Reactive statements help developers avoid manually recalculating values every time data changes.
Updating Reactive Data
Add buttons to change the quantity:
<script>
let price = 20;
let quantity = 1;
$: total = price * quantity;
function increaseQuantity() {
quantity += 1;
}
</script>
<h2>Quantity: {quantity}</h2>
<h2>Total: ${total}</h2>
<button on:click={increaseQuantity}>
Add Item
</button>
Each time the quantity changes, the total updates automatically.
Keeping Data Synchronized
Reactive statements make applications easier to maintain because related values stay synchronized automatically.
Instead of manually updating every dependent value, Svelte handles the updates behind the scenes.
This reactive workflow is one of the reasons Svelte feels very lightweight and developer-friendly.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla