首页 > 解决方案 > 在mounted()中运行循环时浏览器卡住

问题描述

我正在尝试打开一个端点mounted(),我想增加 id 直到它为假,这样我就可以在页面上显示所有结果

  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);
  }

为什么浏览器会卡住?我的循环中有什么东西吗?

标签: javascriptvue.js

解决方案


我的循环中有什么东西吗?

是的:你永远不会this.id在循环中改变。该循环只是在 HTTP 请求之后的 HTTP 请求之后创建 HTTP 请求,因为您的增量this.id在您的回调then,这是异步的。

将增量移到then回调之外,以便循环真正完成。


将您的编辑替换while (this.id <= 10)while (this.found),这是同样的问题:没有任何设置this.found


推荐阅读