How to handle the events in Svelte
In this tutorial, we are going to learn about event handling in svelte with the help of an example.
Svelte offers us an on:
directive which helps us to listen the dom events.
Counter Example
<script>
let count = 1;
function inc(){
count = count+1;
}
</script>
<div>
<h1>{count}</h1>
//listening click event on a button <button on:click={inc}>Increment</button></div>
In the above code, we are listening for a click event on a button so that whenever a user clicks on a button we are invoking the inc
handler method attached to it.
Passing arguments to event handler
To pass the arguments to an event handler, we need to use a arrow function which is invoking the event handler with an argument.
<script>
let count = 1;
function inc(num){ count = count+num;
}
</script>
<div>
<h1>{count}</h1>
<button on:click={() => inc(2)} >Increment</button></div>
Inline event handlers
In svelte, we can also use inline event handlers without losing any performance in the app.
example:
<button
on:click={() => {count = count + 1;}}> Increment
</button>