Javascript 修改数据后VueJS不会重新渲染
我和VueJS相处得很艰难。在我的一个组件中,我以对象数组的形式从后端检索数据。检索到这些数据后,我使用Javascript 修改数据后VueJS不会重新渲染,javascript,vue.js,Javascript,Vue.js,我和VueJS相处得很艰难。在我的一个组件中,我以对象数组的形式从后端检索数据。检索到这些数据后,我使用forEach循环遍历它,并在每个对象中添加一个字段 ... {{comment.content} PAR——{{注释}作者} ... 从“./services/post”导入{getPost}; 从“./services/comment”导入{getComments}; 从“./services/user”导入{getUser}; 导出默认值{ 姓名:"职位",, 数据(){ 返回{ po
forEach
循环遍历它,并在每个对象中添加一个字段
...
{{comment.content}
PAR——{{注释}作者}
...
从“./services/post”导入{getPost};
从“./services/comment”导入{getComments};
从“./services/user”导入{getUser};
导出默认值{
姓名:"职位",,
数据(){
返回{
post:null,
评论:[],
posted:null,
等待评论:对
}
},
异步创建(){
this.postId=this.$route.params.id;
this.post=等待getPost(this.$route.params.id);
let allComments=wait getComments(this.postId);
allComments.forEach(异步注释=>{
let author=wait getUser(comment.author\u id);
comment.author=author.firstname+“”+author.lastname;
});
this.comments=所有注释;
this.waitingForComments=false;
}
}
在
中,“--”显示没有问题,但是注释。作者不打印任何内容!然而Vue的Chrome调试器显示author字段确实包含值
我真的不明白这是从哪里来的。我尝试在forEach()
前面使用wait
,我还尝试在comments
上使用观察者,并检索该观察者中的作者。但什么都不管用
任何帮助都将不胜感激 使用
this.$set(this, "comments", allComments);
反而
this.comments = allComments;
foreach函数的工作方式与.map函数不同。Map返回一个数组,但foreach不返回
为您创建的函数复制/粘贴以下内容:
async created() {
this.postId = this.$route.params.id;
this.post = await getPost(this.$route.params.id);
let allComments = await getComments(this.postId);
this.comments = allComments.map(async comment => {
let author = await getUser(comment.author_id);
comment.author = author.firstname + " " + author.lastname;
return comment;
});
this.waitingForComments = false;
}
但是,这个迭代有一个问题,要查看结果,必须让查询结束。因此,需要在created()函数中添加以下代码
this.waitingForComments = true;
const results = await Promise.all(this.comments);
this.waitingForComments = false;
可能是因为我没有检查它,所以它不起作用。但是请尝试一下,我希望它对您有用。我不会将forEach
与async/await
一起使用:请参阅
我想这就是你的本意:forEach不等待;)
一个很好的ol'。。。of
就行了
async created() {
this.postId = this.$route.params.id;
this.post = await getPost(this.$route.params.id);
let allComments = await getComments(this.postId);
for(let comment of allComments){
let author = await getUser(comment.author_id);
comment.author = `${author.firstname} ${author.lastname}`;
}
this.comments = allComments;
this.waitingForComments = false;
}
是的,很管用!谢谢但我真的不明白发生了什么,尤其是你在做什么。映射完结果后,this.comments
数组不应该只是一个对象吗?