如何在 Svelte 中创建派生变量?

How to make derived variable in Svelte?

我有两家商店:

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

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

您可以设置一些本地 variables/functions,例如:

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

使用 derived store:

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
)