typescript 如何从为svelte中的每个添加的组件中获取值?

w80xi6nr  于 2023-01-06  发布在  TypeScript
关注(0)|答案(2)|浏览(123)

我是新的前端和苗条和实验的一些东西。
我有以下计数器组件,其中包含用于项目的递增/递减按钮:
Counter.svelte

<script>
    export let amount = 0;
    function increment() {
        amount += 1;
    }

    function decrement() {
        if (amount > 0) {
            amount -= 1;
        }
    }
</script>

<button on:click={decrement}>-</button>{amount}<button on:click={increment}>+</button>

App.svelte

<script>
... import stuff

    let items=[{ //data from rest
      id: 1,
      name: potato,
      price: 5
    }, {
      id: 2,
      name: garlic,
      price: 3
    }, {
      id: 3,
      name: rice,
      price: 10
    }];

    function purchase() {
        //TODO use JSON generated in POST
    }
</script>

{#each items as item}
    {item.name} <Counter></Counter>
{/each}

<button on:click={purchase}>Purchase</button>

当我点击按钮后,为项目选择的数量不为0时,我如何生成下面的JSON?(假设大蒜数量为0)

[{
      id: 1,
      name: potato,
      price: 5,
      amount: 30
    },{
      id: 3,
      name: rice,
      price: 10,
      amount: 400
    }];
6vl6ewon

6vl6ewon1#

可以将#each循环内的值绑定到单个item的属性

{#each items as item}
    {item.name} <Counter bind:amount={item.amount}/>
{/each}

该属性尚不存在,但由于在Counter中设置了默认值

export let amount = 0;

它将被初始化为零。所有对金额的更改都将直接更改items。因此,在purchase中,只需过滤items中的金额

function purchase() {
        const itemsWithAmount = items.filter(i => i.amount > 0)
        console.log(itemsWithAmount)
    }

REPL

<script>
    import Counter from './Counter.svelte'

    let items=[{
        id: 1,
        name: 'potato',
        price: 5
    }, {
        id: 2,
        name: 'garlic',
        price: 3
    }, {
        id: 3,
        name: 'rice',
        price: 10
    }];

    $: console.log(items)

    function purchase() {
        const itemsWithAmount = items.filter(i => i.amount !== 0)
        console.log(itemsWithAmount)
    }
</script>

<ul>
    {#each items as item}
    <li>
        {item.name} <Counter bind:amount={item.amount}/>
    </li>
    {/each}
</ul>

<button on:click={purchase}>Purchase</button>
mbjcgjjk

mbjcgjjk2#

您可能希望在获取数据后将所有项的amount属性初始化为0,然后将其绑定到Counter

<Counter bind:amount={item.amount} />

bind将更改从组件传播到条目对象。
purchase中,您只需要过滤项目,类似于:

const toBuy = items.filter(x => x.amount > 0);

相关问题