gpt4 book ai didi

javascript - 让 Vue.js 使用 $set() 检测数组的更改

转载 作者:行者123 更新时间:2023-11-28 18:46:42 24 4
gpt4 key购买 nike

我在更新显示为列表的数组时遇到问题。我试图让 Vue 使用 $set() 检测更改(如 documentation 中所述),但我无法使其工作。

这是我的代码:

this.choices = this.currentScene.choices;
for (i = 0; i < this.choices.length; i++) {
choice = this.currentScene.choices[i];
choice.parsedText = this.parseText(choice.text);
this.choices.$set(i, choice);
}

Vue 仍然不更新 View 。我究竟做错了什么?提前致谢!

编辑:是的,“this”指的是 Vue 实例。

最佳答案

拥有代码的 JSfiddle 肯定会很有用,但无论如何我都会尝试一下。

我不确定您是否需要使用该函数来更新数组,因为正如文档指出的那样,仅当您需要更改项目的索引时才使用该函数。

JavaScript 有一个名为 .map 的内置函数,它接受回调函数并返回一个新数组,并将回调应用于每个项目。

例如,您可以将您的函数翻译成这样,假设 .parseText 是 Vue 类上的一个方法。

var self = this; // so that we can access the Vue class inside map

this.choices = this.currentScene.choices.map(function(choice) {
choice.parsedText = self.parseText(choice.text);
return choice;
});

Vue 应该接受这些更改。

关于javascript - 让 Vue.js 使用 $set() 检测数组的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com