vue 中axios 循环请求会影响什么结果

vue 中axios 循环请求会造成什么影响,对请求的结果造成什么影响

由于闭包的影响,循环中进行axios请求会导致循环变量i是固定值如图
在这里插入图片描述
在这里插入图片描述
错误代码:

   for (var j = 0; j < this.$store.state.dictionary.dictionary.items.length; j++) {
          var that = this
          index = j
         this.$store.state.dictionary.dictionary.items[index].children= []
            if (that.$store.state.dictionary.dictionary.items[index].dataDictionaryType == 10) {
             var promiseAll = that.$store.state.dictionary.dictionary.items.map(function(){
            return that.$axios.get( "/api/app/data-dictionary-item/children/" +
            that.$store.state.dictionary.dictionary.items[index].id,  {
                  headers: {
                    Authorization: "Bearer " + sessionStorage.access_token,
                  },
                })
          })
          that.$axios.all(promiseAll).then(function(resArr){
            console.log(index)
            that.tableData2[index].children = resArr[index].data.items
          })
          }

导致循环变量的值是定值
解决办法:使用闭包 防止变量污染
正确代码

  for (var j = 0; j < this.$store.state.dictionary.dictionary.items.length; j++) {
          var that = this
          index = j
         this.$store.state.dictionary.dictionary.items[index].children= []
            if (that.$store.state.dictionary.dictionary.items[index].dataDictionaryType == 10) {
            (function(index){
                var promiseAll = that.$store.state.dictionary.dictionary.items.map(function(){
            return that.$axios.get( "/api/app/data-dictionary-item/children/" +
                  that.$store.state.dictionary.dictionary.items[index].id,  {
                  headers: {
                    Authorization: "Bearer " + sessionStorage.access_token,
                  },
                })
          })
          that.$axios.all(promiseAll).then(function(resArr){
            console.log(index)
            that.tableData2[index].children = resArr[index].data.items
          })
            })(index)
          }
          this.tableData2 =this.$store.state.dictionary.dictionary.items;
        }

在这里插入图片描述
循环变量的值正常显示,由于我这里加的有判断条件,所以打印结果是0 1 2 3 4 8 9
判断条件去了就显示的是 0 1 2 3 4 5 6 7 8 9
循环变量正常之后,就可以进行正常传值操作了

猜你喜欢

转载自blog.csdn.net/weixin_40648700/article/details/112367364
今日推荐