【问题标题】:Passing multiple parameters on Svelte action在 Svelte 动作上传递多个参数
【发布时间】:2020-03-20 04:22:28
【问题描述】:

根据 Svelte 文档:

动作是在创建元素时调用的函数。他们可以返回一个带有在元素卸载后调用的destroy方法的对象

我想将多个参数传递给一个 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>

【问题讨论】:

    标签: javascript svelte


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你也可以使用数组。

      在我的代码的 sn-p 下方:

      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 = '';
            }
          };
        };
      };
      

      此代码将对象呈现到表&lt;td&gt; 节点中。正则表达式流用于搜索节点并标记搜索结果。

      下面的代码显示了 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 以允许在使用指令中使用对象和类方法。

      【讨论】:

        猜你喜欢
        • 2021-12-08
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 1970-01-01
        • 1970-01-01
        • 2022-10-18
        • 2023-04-07
        相关资源
        最近更新 更多