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
循环变量正常之后,就可以进行正常传值操作了