在 Svelte 中同步 Class 状态

Sync Class state in Svelte

我有一个 class 有一些更新其状态的方法。 class 的真实状态在 Svelte 中不同步,我知道这是正确的行为,因为没有新的分配。确保对象状态与 DOM 保持同步的最佳方法是什么?

这是一个 REPL 示例:https://svelte.dev/repl/394676df2221456d923f23acc03c3f76?version=3.46.4

您可以使用 writable 家商店:

Function that creates a store which has values that can be set from 'outside' components.

工作示例:https://svelte.dev/repl/e7bb5633696d4e939c90f701bce2cfb2?version=3.46.4


您可以像 Custom stores 教程中那样创建自定义商店,例如:

export function makeUser(name, age){
    const {update, subscribe} = writable({
        loading: false,
        name,
        age
    })
    
    return {
        incrementAge: async () => {
          update((s) => ({...s, loading: true}))
            
          await new Promise(r => setTimeout(r, 2000))
        
          update((s) => ({...s, age: s.age + 1, loading: false }))
        },
        subscribe,
    }
}

工作示例:https://svelte.dev/repl/4ff2b92282b8455387357529ccb9e3a9?version=3.46.4