javascript - 如何在 svelte 中创建响应式类

标签 javascript svelte svelte-store

我正在将我的代码库迁移到 svelte。我的业务逻辑包含很多类,它们相互依赖。我创建了一个 REPL 来可视化我的问题:Link .

在这个例子中,如果直接更改为 html 内联函数(左键),则 person 的 money 属性只会在 UI 中正确更新。当调用类方法(右键)时,类的状态会更新,UI 不会。

我知道这种行为是有意为之的,可写对象应该用于在 svelte 组件之外实现 react 性。是否有可能通过使用 REPL 中的类来实现 react 性?为了修复我的 REPL,我需要用可写对象替换它们的属性吗?如果是,怎么办?

<div id="app">
    {#each teams as team}
        <div>
            {#each team.people as person}
                <li class="person-row">
                    <div>{person.name}</div>
                    <div>{person.money}€</div>
                    <button on:click={() => (person.money += 1)}>Add 1€ </button>
                    <button on:click={() => person.addMoney(1)}>Add 1€ </button>
                </li>
            {/each}
        </div>
    {/each}
</div>

<script>
    class Person {
        constructor(name, money) {
            this.name = name;
            this.money = money;
        }

        addMoney(x) {
            this.money += x;
        }
    }

    class Team {
        constructor(name, people) {
            this.name = name;
            this.people = people;
        }
    }

    const p1 = new Person("Person 1", 1000);
    const p2 = new Person("Person 2", 2);
    const p3 = new Person("Person 3", 60);
    const p4 = new Person("Person 4", 15);
    const t1 = new Team("Team 1", [p1, p2]);
    const t2 = new Team("Team 2", [p3, p4]);

    const teams = [t1, t2];
</script>

<style>
    .person-row {
        display: flex;
        flex-direction: row;
    }

    .person-row * {
        width: 100px;
    }
</style>

最佳答案

一种可能的解决方法是将属性重新分配给自身,如下所示:

<button on:click={() => { person.addMoney(1); person.money = person.money; }}

或者如果您希望避免显式重新分配,您还可以从 addMoney() 方法返回 money 属性

addMoney(x) {
  this.money += x;
  return this.money;
}

所以按钮可以是

<button on:click={() => { person.money = person.addMoney(1); }}

关于javascript - 如何在 svelte 中创建响应式类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71337785/

相关文章:

javascript - Svelte 派生存储和数组排序

Svelte 将参数添加到派生状态并保持其 react 性

javascript - React Redux - bool 值未定义

javascript - polymer 铁型 react

javascript - 我可以查看 window.history.back() 会将用户带到哪个站点吗?

javascript - 通过单击按钮保存项目变量

svelte - 使用选择框的奇怪 Svelte react 行为

javascript - 是否有默认的 JavaScript 文件命名约定?

javascript - 钩子(Hook)中的 SvelteKit externalFetch 函数永远不会被调用