0

我想创建一个对象作为存储,其中对象中的数组也可以用作存储。每个数组都需要更新(订阅),对象也需要更新到本地存储。

这是对象的结构

{
   "expenses":[
      {
         "name":"sam",
         "id":1
      },
      {
         "name":"bob",
         "id":2
      }
   ],
   "options":[
      ...
   ]
}

这是我到目前为止的代码:

import { writable } from "svelte/store";

// get local storage
let storage = localStorage.getItem("userInputs");

// if storage exists, use it. otherwise set empty array
export let userInputs = writable(JSON.parse(storage) || []);
export let userExpenses = writable(storage.expenses || []);
export let userOptions = writable(storage.options || []);

// subscribe inputs to localStorage
userInputs.subscribe((val) =>
    localStorage.setItem("userInputs", JSON.stringify(val))
);

我希望能够在整个应用程序中使用userExpensesuserOptions作为商店。当这些数组更新时,它们需要在主userInputs对象中更新,这需要推送到 localStorage。

谢谢

4

1 回答 1

1

您可以为此使用 svelte 的超棒派生函数,例如

// create userInputs as derived which results in a store
// that is updated whenever userExpenses or userOptions
// are.
const userInputs = derived(
   [userExpenses, userOptions], 
   ([ue, uo]) => ({
      userExpenses: ue,
      userOptions: uo
   })
);

// sync to localStorage
userInputs.subscribe(val => {
    localStorage.setItem("userInputs", JSON.stringify(val));
});
于 2021-05-20T14:03:59.900 回答