我正在尝试获取mounted()
上的端点,我想增加id直到它为false,以便我可以在页面上显示所有结果
data () {
return {
id : 0,
found : true,
}
},
mounted(){
while(this.found){
this.$http.get(`https://jsonplaceholder.typicode.com/todos/${this.id}`)
.then((data)=>{
this.characters = data.body
this.id++;
})
console.log(this.id);
}
为什么浏览器无法启动?我的循环中有东西吗?
循环中有东西吗?
是:您永远不会在循环中更改this.id
。该循环仅在HTTP请求之后的HTTP请求之后创建HTTP请求,因为您的this.id
增量是inside您的then
回调,这是异步的。
将增量移到then
回调之外,这样循环实际上就结束了。
将您的编辑用while (this.id <= 10)
替换while (this.found)
,这是同样的问题:没有设置this.found
。
问题是您的循环永远不会结束,因为this.id
永远都是一样的。您必须像将我的上下文“存储”到此变量中一样:
data () {
return {
id : 0,
found : true,
}
},
mounted(){
let t = this;
while(t.id <= 10){
this.$http.get(`https://jsonplaceholder.typicode.com/todos/${this.id}`).then((data)=>{
t.characters = data.body
t.id++;
});
console.log(t.id);
}
}