Accordingly to the Svelte documentation:
Actions are functions that are called when an element is created. They can return an object with a destroy method that is called after the element is unmounted
I want to pass multiple parameters to a Svelte action function, but only the last one is recogonized
DEMO
<script>
function example(node, arg1, arg2) {
// the node has been mounted in the DOM
console.log(arg1, arg2) // Should display 'a b', but actually only displays 'b undefined'
return {
destroy() {
// the node has been removed from the DOM
}
}
}
</script>
<h1 use:example={'a', 'b'}>Hello World!</div>
Is there any viable solution that avoid the use of a single object as parameter?
<script>
function example(node, arg) {
// the node has been mounted in the DOM
console.log(arg) // Returns a object with the arguments
return {
destroy() {
// the node has been removed from the DOM
}
}
}
</script>
<h1 use:example>Hello World!</div>
<!-- Passing parameters -->
<h1 use:example={{
arg1: [50, 75, 100],
arg2: true
}}>Works like a charm!</h1>
The content between {} can be any JavaScript expression, and when you write 'a', 'b' you are using the comma operator, so the value of the entire expression will be 'b'.
You could use an array instead.
Example (REPL)
<script>
function example(node, [arg1, arg2]) {
console.log(arg1, arg2)
return {
destroy() {
// the node has been removed from the DOM
}
}
}
</script>
<h1 use:example="{['a', 'b']}">Hello World!</h1>
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