I know there are slots and some discussion about slots without DOM elements. What about custom directives? (That is, special "atributes" that will modify the behavior of a component/DOM element)
There are no custom directives just yet like you might find in Vue, but you can certainly bind actions to child elements with use:something
. See the docs here. You can also find an official example here.
Here's a small example:
<button on:click={doSomething} use:tooltip={calculatedTooltip}>
Click Me
</button>
Coming from an Angular background, I wondered the same. I was happy to see there's something similar in Svelte thanks to GoogleMac
's answer.
If you are used to Angular, you'd probably be looking for event dispatches too (@Output
in Angular). It seems like there's not such a concept in Svelte's actions but you can make use of parameters
. Here's an example:
// outside-click.js => Action
export function outsideClick(node, onOutsideClick) {
// ^^^^^^^^^^^^^^ parameter
function handleClick ({ target }) {
const clickedOutside = !node.contains(target);
if (clickedOutside) {
onOutsideClick();
}
}
window.addEventListener('click', handleClick);
return {
destroy () {
window.removeEventListener('click', handleClick);
}
};
}
// MyComponent.svelte => component
<script>
function hideMenu() {
// hide menu logic
}
</script>
<div use:outsideClick={hideMenu} class="menu">
<!-- Menu that has to be closed when clicking outside of it -->
</div>
Hope this would help someone.
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