如何使用 Svelte 传播道具

How to spread props using Svelte

我正在使用嵌套组件,我想为该嵌套组件设置整个 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 }}" />

目前没有像 <NestedComponent ...forNested> 这样的 'spread operator',尽管我们将来会添加类似的东西并不是不可想象的。目前,最简洁的数据向下传递方式是使用:foo指令,即foo={{foo}}:

<NestedComponent :a :b/>

我使用 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 也行

Actually I just tried and YES you can spread props.

父组件

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