英文:
Why is my Svelte project not updating the DOM when using a non-inline function for a boolean array element toggle?
问题
在一个 Svelte 项目中,尝试通过一个由 onclick 事件触发的函数来更新布尔数组元素,似乎会更新相关的值,但更新不会在 DOM 中反映出来。使用内联函数进行相同操作会如预期地更新 DOM。这里展示了两种情况:
<script>
let array = [{'truth': false}, {'truth': false}];
function toggleTruth(el) {
console.log("el 初始值为", el.truth);
el.truth = !el.truth
console.log("el 最终值为", el.truth);
}
</script>
{#each array as element}
<h1 on:click={() => element.truth = !element.truth}>(内联)Truth 是 {element.truth} (达到我的目标)</h1>
<h1 on:click={() => toggleTruth(element)}>(外部函数)Truth 是 {element.truth} (不符合我的预期,但根据控制台日志,某些内容已被更新)</h1>
{/each}
如何确保非内联方法能够如我所期望地更新 DOM?
我所做的事情:
我添加了一个在点击事件上调用的函数,它会对数组中的布尔元素进行取反操作。
预期行为:
DOM 反映布尔元素值的变化。
实际行为:
DOM 没有更新,但控制台日志显示数组元素已被更新。
英文:
In a Svelte project, attempting to update a boolean array element via a function triggered by an onclick event appears to update the relevant value, but the update is not reflected in the DOM. Doing the same using an inline function updates the DOM as intended. Both scenarios are illustrated here:
<script>
let array = [{'truth': false}, {'truth': false}];
function toggleTruth(el) {
console.log("intial val of el is", el.truth);
el.truth = !el.truth
console.log("final val of el is", el.truth);
}
</script>
{#each array as element}
<h1 on:click={() => element.truth = !element.truth}>(inline)Truth is {element.truth} (Does what I want)</h1>
<h1 on:click={() => toggleTruth(element)}>(ext function)Truth is {element.truth}(Doesn't do what I want, but based on the console logs something is being updated)</h1>
{/each}
How can I ensure that the non-inline approach results in the DOM being updated as I expect?
What I've done:
I've added a function to be called on click events, which negates a boolean element in an array.
Expected behaviour:
The DOM reflects the change in the value of the boolean element.
Actual behaviour:
The DOM is not updated, but console logging reveals that the array element is being updated.
答案1
得分: 0
添加一个将数组分配给自身的赋值,以便进行更改的注册并更新DOM。
function toggleTruth(el) {
console.log("el的初始值为", el.truth);
el.truth = !el.truth;
array = array;
console.log("el的最终值为", el.truth);
}
英文:
Add an assignment of the array to itself so that the change is registered and the DOM is updated
function toggleTruth(el) {
console.log("intial val of el is", el.truth);
el.truth = !el.truth
array = array
console.log("final val of el is", el.truth);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论