【问题标题】:How to make derived variable in Svelte?如何在 Svelte 中创建派生变量?
【发布时间】:2020-11-02 22:36:15
【问题描述】:

我有两家商店:

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

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

【问题讨论】:

    标签: javascript svelte svelte-3 svelte-store


    【解决方案1】:

    使用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
    )
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-04-08
        • 1970-01-01
        • 2013-11-22
        • 1970-01-01
        • 2020-09-30
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多