[英]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教程中所述(顺便读一读),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
是从外部来源获得的,则可能更简单)是在调用testFunction
之后重新分配a
:
setTimeout(() => {
testFunction(a);
a = a
},1000);
这行得通,但感觉有点不雅致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.