svelte 如何处理导入中的反应性

How does svelte handle reactivity inside imports

我有一个被导入函数改变的对象。

https://svelte.dev/repl/e934087af1dc4a25a1ee52cf3fd3bbea?version=3.12.1

我想知道如何让我的更改反映在我的测试变量中

// app.svelte
<script>
import {testFunction} from "./Simulations.js";

let a = [{"b":1}, {"b":2}];
$:test = a;

setTimeout(() => {
    // this function changes the value of a
    // while not reflecting the changes in test
    testFunction(a);
    // the code commented below works
    //a[0].b = 55;
    console.log("Value changed asdasda") 
},1000);

</script>

{#each test as t}
    This is a test value: {t.b} <br/>
{/each}


// simulation.js
function testFunction(variable){
// this code changes the value of the object dutifully
// it seems however that the change is not picked up
// by the reactive variable
    variable[0].b = 55;
}

export {testFunction}

Svelte Tutorial 中所述(顺便说一下,这是一本好书),Svelte 仅对当前组件中的分配做出反应。当改变其他文件中的变量时,Svelte 无法拾取它。

一个可能的解决方案是 return 来自 testFunction 的变异数组并分配它:

// app.svelte
setTimeout(() => {
    a = testFunction(a);
},1000);

// simulation.js
function testFunction(variable){
    variable[0].b = 55;
    return variable;
}

如果这样做,则根本不需要 test 变量:

<script>
    import {testFunction} from "./Simulations.js";

    let a = [{"b":1}, {"b":2}];

    setTimeout(() => {
        a = testFunction(a);
    },1000);
</script>

{#each a as val}
    This is a test value: {val.b} <br/>
{/each}

编辑:我还应该提到最简单的修复(如果 testFunction 来自外部来源,可能更容易)是重新分配 a 在调用 testFunction:

之后
setTimeout(() => {
    testFunction(a);
    a = a
},1000);

这个可以,但是感觉有点不雅。