问题描述
我有两家商店:
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;
}
一定有更好的方法,我听说过派生商店,但在这种情况下我不知道如何使用它。
解决方法
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
)
,
您可以设置一些局部变量/函数,例如:
<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>