event
The basic use
<script>
function handleClick() {
console.log('event handler is working');
}
</script>
<! On :click="{handleClick}" <=> on:click={handleClick} On :click="{handleClick}" syntax highlighting may exist, and another may not -->
<button on:click="{handleClick}">Click me to trigger the event</button>
Copy the code
Inline event
<! Inline events are not recommended in some frameworks, especially in loops, as this often means that multiple functions of the same type may be created, resulting in a loss of performance. However, this rule does not apply to Svelte. Whichever form you choose, the compiler will always do the right thing.
<button on:click="{() => console.log('event handler is working')}">Click me to trigger the event</button>
Copy the code
Event modifier
Svelte allows us to use event modifiers to restrict the execution and firing of our event handlers
The modifier | role |
---|---|
preventDefault | Called before running the event handlerevent.preventDefault() To block the default event |
stopPropagation | callevent.stopPropagation() Stops event bubbling to prevent the event from propagating to the next element |
passive | – Improved scroll performance for Touch/scroll events (Svelte automatically adds it in a safe place by default), i.e. execute the event’s default behavior without having to check whether the default behavior is prevented (so passive and preventDefault fail) |
nonpassive | Explicitly setpassive: false |
capture | incapturePhase triggers the handler instead ofThe bubblingphase |
once | Remove it immediately after running an event handler |
self | The event handler is fired only if the event.target is the element itself (that is, if the event is triggered by its own element) |
<! Basic use of event modifiers -->
<button on:click|once={handleClick}>
Click me
</button>
<! ----------------------------------->
<! -- Event modifiers -->
<button on:click|once|preventDefault|self={handleClick}>
Click me
</button>
Copy the code
Component events
Some use of child components requires sending (dispath) events to the parent component (either native DOM events or user-defined events),
For example, when a child component communicates with its parent (data passing). To do this, you need to create an event Dispatcher.
<! -- Subcomponent -->
<script>
// Introduce the event dispenser creation method
import { createEventDispatcher } from 'svelte'
// The event distributor must be created when the component is initialized -- in the top-level script scope
// So that svelte can bind the event distributor to the component instance object
// This means that it makes no sense to generate event dispatchers in timers or function methods such as sayHello
const dispatch = createEventDispatcher();
function sayHello() {
// dispath(event name, data to pass)
// The data to be passed can be of any data type, in this case objects
dispatch('message', {
msg: 'Hello Svelte'})}</script>
<button on:click={sayHello}>
Click to say hello
</button>
Copy the code
<! -- Parent component -->
<script>
import Inner from './Inner.svelte';
function handleMessage(event) {
// The data passed in by the child component will be stored in event.detail
// Since this is an object, we can use point syntax to get the value
alert(event.detail.msg);
}
</script>
<! The handleMessage method is triggered when a child component fires a custom message method.
<Inner on:message={handleMessage}/>
<! ---------------------------------------------->
<! -- This is another parent component -->
<script>
import Inner from './Inner.svelte';
</script>
<! The parent component does not have the message event response code. When the child component triggers the message event, the parent component knows that the child component has violated the message event. However, since there is no corresponding event response function, no error will be reported at this time.
<Inner />
Copy the code
Event forwarding
Unlike DOM events, component events do not bubble
If you want to listen for an event on a deeply nested component, the intermediate component must forward the event.
Intermediate component
<script>
import Inner from './Inner.svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function forward(event) {
dispatch('message', event.detail);
}
</script>
<Inner on:message={forward}/>
Copy the code
There is a lot of code in the intermediate component that forwards the child component events to the parent component
This code is obviously redundant, so Svelte gives us a syntactic sugar
<script>
import Inner from './Inner.svelte';
</script>
<! -- If we write only the event name, but not the value, it means "forward all events of the same type".
<Inner on:message/>
Copy the code
We can forward not only custom events, but also native DOM events in Svelte
<! -- Subcomponent -->
<! -- If this is a component, the event handling of the component should not be implemented by the component, but should be implemented by the user of the component, that is, the parent component, according to the specific needs of the component, so we just need to listen for the corresponding event and forward to the parent component.
<button on:click>
Click me
</button>
<! -------------------------------------------------->
<! -- Parent component -->
<script>
import CustomButton from './CustomButton.svelte';
function handleClick() {
// When the child triggers the click event, it forwards it to the parent
// The parent component then triggers the click event and triggers the logical code in the function
alert('Button Clicked');
}
</script>
<CustomButton on:click={handleClick}/>
Copy the code