gpt4 book ai didi

javascript - 在 Svelte Action 上传递多个参数

转载 作者:行者123 更新时间:2023-11-30 19:05:42 25 4
gpt4 key购买 nike

根据 Svelte 文档:

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

我想将多个参数传递给 Svelte Action 函数,但只有最后一个被识别

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>

是否有任何可行的解决方案可以避免使用单个对象作为参数?

<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>

最佳答案

{} 之间的内容可以是任何 JavaScript 表达式,当您编写 'a', 'b' 时,您使用的是 comma operator ,所以整个表达式的值将是 'b'

您可以改用数组。

示例 ( 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>

关于javascript - 在 Svelte Action 上传递多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com