Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
In Svelte you can listen for changes in the component state, and update other variables.
For example if you have a count
variable:
<script>
let count = 0
</script>
and you update it by clicking a button:
<script>
let count = 0
const incrementCount = () => {
count = count + 1
}
</script>
{count} <button on:click={incrementCount}>+1</button>
You can listen for changes on count
using the special syntax $:
which defines a new block that Svelte will re-run when any variable referenced into it changes.
Here’s an example:
<script>
let count = 0
const incrementCount = () => {
count = count + 1
}
$: console.log(`${count}`)
</script>
{count} <button on:click={incrementCount}>+1</button>
I used the block:
$: console.log(`${count}`)
You can write more than one of them:
<script>
$: console.log(`the count is ${count}`)
$: console.log(`double the count is ${count * 2}`)
</script>
And you can also add a block to group more than one statement:
<script>
$: {
console.log(`the count is ${count}`)
console.log(`double the count is ${count * 2}`)
}
</script>
I used a console.log() call in there, but you can update other variables too:
<script>
let count = 0
let double = 0
$: {
console.log(`the count is ${count}`)
double = count * 2
console.log(`double the count is ${double}`)
}
</script>
Download my free Svelte Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More svelte tutorials:
- Getting started with Svelte - a short tutorial
- How to work with props in Svelte
- How to import components in Svelte
- How to export functions and variables from a Svelte component
- Svelte templates: conditional logic
- How to rerender a Svelte component on demand
- Svelte Slots
- How to add comments in Svelte templates
- Svelte Bindings
- Handling State Updates in Svelte
- Reactive Statements in Svelte
- Svelte Lifecycle Events
- Svelte templates: loops
- Resolve promises in Svelte templates
- Working with events in Svelte
- Cross-component State Management in Svelte
- How to access a URL parameter in Sapper outside of script module
- How to dynamically apply CSS in Svelte
- How to redirect to a URL in Sapper
- How to simulate a for loop in Svelte templates