Reputation: 495
This afternoon I was practicing a bit with vuejs. Simply use axios to get some data. I succeeded in retrieving data. But then I encountered a problem with the for loop.
If I do this
<template></template>
<script>
export default {
data: function() {
return {
arr: []
}
},
created() {
axios.get('url')
.then(function(res) {
for (var i = 0; i <= res.length; i++) {
if (true) {
// If i assign the value to the 'array' here, the for loop will stop
this.arr.push('something')
// I have also tried this.$data.arr
}
}
})
.catch(err=>console.log(err));
}
}
</script>
So I changed a bit and it worked
<script>
export default {
data: function() {
return {
arr: []
}
},
created() {
var second_arr = []; // Defined a variable here
axios.get('url')
.then(function(res) {
for (var i = 0; i <= res.length; i++) {
if (true) {
// Working with 'second_arr' variable instead of the 'arr' variable in the data
second_arr.push = something;
}
}
})
.catch(err=>console.log(err));
//then assign 'second_arr' to 'arr' in the data
this.arr = second_arr;
}
}
</script>
The question is
1. In the first code, why does the loop only run once?
2. I have tried to find out and found a few comments about 'scope'. So can someone explain more clearly to me? Thanks.
Upvotes: 0
Views: 58
Reputation: 487
I'm pretty sure your data are not in response
but in response.data
As you can see when you console.log(response.length)
console's returns undefined
but when you console.length(response.data.length)
it returns 1
EDIT : In my exemple case, there's only one object in data, maybe in your case it will be more than 1
Upvotes: 0
Reputation: 1180
All action must take place in then
as axios do asychronous call, and scope this
in function has another value:
var that = this;
var second_arr = []; // Defined a variable here
axios.get('url')
.then(function(res) {
for (var i = 0; i <= res.length; i++) {
if (true) {
second_arr.push = something;
}
}
that.arr = second_arr;
})
.catch(err=>console.log(err));
Upvotes: 1
Reputation: 124
In the first code this in then function is undefined, you can use arrow funtion to bind this
.then((res) => {
for (var i = 0; i <= res.length; i++) {
if (true) {
// If i assign the value to the 'array' here, the for loop will stop
this.arr.push('something')
// I have also tried this.$data.arr
}
}
})
like this
Upvotes: 1