【问题标题】:How to spread props using Svelte如何使用 Svelte 传播道具
【发布时间】:2017-08-22 20:04:02
【问题描述】:

我正在使用嵌套组件,我想为该嵌套组件设置整个 data 属性,并使用父组件中的值。

比如第一个app.html组件

<NestedComponent data="{{ forNested }}" />
<script>
  export default {
    data: () => {
      return { forNested: { a: 1, b, 2 }};
    }
  };
</script>

那么嵌套组件nested-component.html 将是:

<p>Hi {{ a }} and {{ b }}</p>

这意味着我必须这样做:

<p>Hi {{ data.a }} and {{ data.b }}</p>

是否有某种关键字属性可以做到这一点?


更新

由于没有展开运算符,我做了这样的事情,您可以在其中设置任意字段,例如data,然后观察它以更新所有属性。在嵌套组件中:

<div class="stuff">{{ someProperty }}</div>
<script>
export default {
  oncreate: function() {
    // Allow data to set all propeties, since we can't set
    // all from the markup of a component
    this.observe('data', d => {
      if (_.isPlainObject(d)) {
        this.set(d);
      }
    });
  }
}
</script>

然后在使用嵌套组件时,forNestedObject 类似于 { someProperty: 123 }

<NestedComponent data="{{ forNestedObject }}" />

【问题讨论】:

    标签: javascript svelte


    【解决方案1】:

    其实我刚刚试过,可以你可以传播道具了。

    父组件

    <script>
      import HelloWorld from "./HelloWorld.svelte";
      let allProps = {
        first: 'First prop',
        second: 'Second prop'
      };
    </script>
    
    <HelloWorld {...allProps} />
    

    子组件

    <script>
        export let first;
        export let second;
    </script>
    
    First prop: {first} <br>
    Second prop: {second}
    

    See it in action (Codesandbox)

    【讨论】:

      【解决方案2】:

      目前还没有像&lt;NestedComponent ...forNested&gt; 这样的“扩展运算符”,尽管将来我们会添加类似的东西并非不可想象。目前,传递数据最简洁的方法是使用:foo 指令,即foo={{foo}}

      <NestedComponent :a :b/>
      

      【讨论】:

      • 嗨,我想知道这是否已经实现了?这对于将 props 传递到深层组件非常有用。
      • 是的,是的——你可以做&lt;NestedComponent {...props}/&gt;。 Docshere(第三版相关,过几天稳定版)
      【解决方案3】:

      我使用babel + spread operator,这对我有用:

      (精简版:2.16.1)

          {#each grid as row}
              {#each row as cell}
                  <Cell {...cell} />
              {/each}
          {/each}
      

      babel 转换后的样子:

          {#each grid as row}
              {#each row as cell}
                  <Cell {letter: cell.letter, nRow: cell.nRow, nCol: cell.nCol} />
              {/each}
          {/each}
      

      将此is equivalent 精简为以下内容:

          {#each grid as row}
              {#each row as cell}
                  <Cell letter={cell.letter} nRow={cell.nRow} nCol={cell.nCol} />
              {/each}
          {/each}
      

      也许它可以在没有 babel 的情况下工作

      【讨论】:

        猜你喜欢
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 2018-10-20
        • 2023-03-14
        • 2021-09-30
        • 2020-03-07
        • 1970-01-01
        相关资源
        最近更新 更多