如何在 Svelte 中创建更新到本地存储的嵌套数组存储?

How to create a nested array store that updates to local storage in Svelte?

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

这是对象的结构

{
   "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。

谢谢

您可以为此使用 svelte 的出色 derived 函数,例如

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