I want to create a component that will handle on:click
, but without exporting an handleClick
function; this is how it works right now
button.svelte
:
<script lang="ts">
export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined
</script>
<button on:click={handleClick}>
<slot></slot>
</button>
app.svelte
:
<script lang="ts">
import Button from '$lib/button/button.svelte'
</script>
<Button handleClick={() => console.log('click!')}>
Click me!
</button>
How to change the Button element to use on:click
directly in the app component?
app.svelte
:
<Button on:click={handleClick}>
<slot></slot>
</Button>
As per the Svelte documentation:
If the
on:
directive is used without a value, the component will forward the event, meaning that a consumer of the component can listen for it.
So you should be able to do this in button.svelte
:
<button on:click>
<slot></slot>
</button>
And then this should work in app.svelte
:
<script>
import Button from './button.svelte';
const handleClick = (event) => {
// …
};
</script>
<Button on:click={handleClick}>
Foo
</Button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With