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

Man*_*nny 2 javascript svelte svelte-store svelte-3

我有两家店:

export const custom_items = writable([]);
export const another_items = writable([]);
Run Code Online (Sandbox Code Playgroud)

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

{
    id: 123
    amount: 123
    price: 123
}
Run Code Online (Sandbox Code Playgroud)

我想创建自己的派生变量,它将保存两个商店“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;
}
Run Code Online (Sandbox Code Playgroud)

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

rix*_*ixo 5

使用派生商店

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
)
Run Code Online (Sandbox Code Playgroud)