1

我有两家店:

export const custom_items = writable([]);
export const another_items = writable([]);

它们都有对象数组,对象看起来像这样(当然,值不同):

{
    id: 123
    amount: 123
    price: 123
}

我想创建自己的派生变量,它将保存“custom_items”和“another_items”这两个商店的总量。我怎样才能做到这一点?

我只能通过这段代码来做到这一点,但它不是反应式的:

function get_total_amount() {
    let total = 0;
    get(custom_items).every((item) => {
        total += item.amount;
    })
    get(another_items).every((item) => {
        total += item.amount;
    })
    return total;
}

一定有更好的方法,我听说过派生商店,但我不知道在这种情况下如何使用它。

4

2 回答 2

4

使用派生商店

export const custom_items = writable([]);
export const another_items = writable([]);

const get_total = items => items.flat().map(x => x.amount).reduce((t, x) => t + x, 0)
    
export const total = derived(
  [custom_items, another_items], // deps
  items => get_total(items)      // [...values] => derived_value
)
于 2020-11-02T23:54:21.870 回答
1

您可以设置一些局部变量/函数,例如:

<script>

let total_one = 0;

let total_two = 0;

$: total_store_one = get(custom_items).every((item) => {
        total_one += item.amount;
    })
$: total_store_two = get(another_items).every((item) => {
        total_two += item.amount;
    })
$: total = total_store_one + total_store_two;
</script>

并在您的代码中使用这些变量,例如:

<p>Total from store one: {total_store_one}</p>
<p>Total from store two: {total_store_two}</p>
<p>Total: {total}</p>
于 2020-11-02T22:45:04.493 回答