Svelte如何处理进口产品中的反应性

时间:2019-09-18 01:00:09

标签: javascript svelte

我有一个被导入功能更改的对象。

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}

1 个答案:

答案 0 :(得分:1)

Svelte Tutorial中所述(顺便读一读),Svelte仅对当前组件中的分配做出反应。在其他文件中对变量进行突变时,Svelte无法识别。

一种可能的解决方案是从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来自外部,则可能更简单)是在通话后重新分配atestFunction

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

这行得通,但感觉有点不雅致。