在 Svelte 动作上传递多个参数

Passing multiple parameters on Svelte action

根据 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 动作函数,但只有最后一个被识别

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>

您也可以使用数组。

下面是我的代码片段:

export function initMapDesc(mapMark) {

  // make the entry (obj) and the composed search regex reactive
  return (node, [obj, pRex]) => {
    // the node has been mounted in the DOM
    node.innerHTML = mapObj(node, obj, pRex, mapMark);

    return {
      update([obj, pRex]) {
        node.innerHTML = mapObj(node, obj, pRex, mapMark);
      },
      // destroy the node to clear the view (on session change)
      destroy() {
        node.innerHTML = '';
      }
    };
  };
};

此代码将对象渲染到 table <td> 节点中。正则表达式流用于搜索节点并标记搜索结果。

下面的代码显示了use函数的调用。闭包用于将对象传递给 use 函数并接收正则表达式搜索结果。

const mapMark = {         // mapMark Obj
  markedIds: [],          // marked result row ids 
  skipProps: ['kind', 'method', 'type', 'bic']
};
const mapper = initMapDesc(mapMark); 

并在 HTML 中:

<td id="{key}" class="space-normal" use:mapper={[$norm.map[key], $pseudoRex]}></td>

我已提交 proposal 以允许在 use 指令中使用对象和 class 方法。

{}之间的内容可以是任何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>