[英]Vue data value not updating for in function use
所以我试图通过无限滚动延迟加载文章,使用惯性 vue 和 axios,后端是 laravel 6.0。 因为我不想做不必要的请求,所以我将文章总数交给了组件。 我还在跟踪组件数据中已加载文章的数量。
props: {
article_count: Number,
},
data: function () {
return {
loaded: 0,
scrolledToBottom: false,
articles: [],
}
},
加载的文章都被放到了articles
,并且scrolledToBottom
会跟踪用户是否已经滚动到底部。 我已经检查过this
指的是 vue 组件并具有它所具有的数据属性。
methods: {
load: function (nextToLoad) {
for (let i = nextToLoad; i < nextToLoad + 10; i++){
if (this.loaded <= this.article_count){
this.$axios.get(route('api_single_article', i))
.then(response => {
if (response.status == 200 && response.data != null) {
console.log(this.loaded);
this.articles.push(response.data);
}
this.loaded++;
})
.catch(error => {
if (error.response.status != 404) {
console.log(error);
console.log(this.loaded);
this.loaded++;
}
});
}
}
console.log(this.loaded);
},
scroll: function () {
window.onscroll = () => {
let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight === document.documentElement.offsetHeight;
if (bottomOfWindow) {
this.load(this.loaded + 1);
}
}
}
}
奇怪的是,如果我在响应/错误箭头函数中记录this.loaded
,它总是返回 0。如果我在响应之外这样做,它也会返回 0,但如果我记录this
, loaded
属性在尽管每次循环运行时都会记录它,但循环已经运行完毕。 我已经向朋友展示了这个,他也无法解决。 这种行为对我来说似乎很奇怪,我不知道我还应该怎么做,因为我对 vue 非常缺乏经验。
谢谢您的帮助。
可能是并发问题。 请记住, axios 调用是异步的,因此循环将在收到响应之前继续。
因此,可能是同时收到了许多响应,并且此时 看来不会有这种事了。 显然JavaScript 会一个接一个地处理回调。loaded
响应仍然为 0。
我不确定 JavaScript 是如何处理并发增量的,所以我不能完全解释它是如何在这里生效的。
从您的实现来看,您似乎希望将load
函数转换为异步函数(使用async
)关键字,然后在 axios 调用之前使用await
以确保您在发出另一个请求之前已收到响应。
出于兴趣,也许可以查看您的网络选项卡并计算发出的请求数。 我怀疑会有比this.article_count
更多的请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.