I created a vue.js app utilizing single file components. In the data section, I initialized an empty array like this:
data: function () {
return {
teamKeys: []
}
},
Next, I populate this array by pushing values into it within one of my methods:
fetchTeams (token) {
var this_ = this
var url = 'myapiserver.com/teams'
this.axios.get(url, {
params: {
accessToken: token
}
})
.then(function (response) {
var teams = response.data.teams[0].teams
teams.forEach(function (t) {
this_.teamKeys.push(String(t.team_key))
})
})
.catch(function (error) {
console.log(error)
})
},
(updated with actual fetchTeams method) Later on, in another method, I try to iterate over the array using forEach.
fetchRosters (token) {
var teamKeys = this.teamKeys
teamKeys.forEach(function (key) {
console.log(key)
// perform actions here
})
}
These methods are consecutively called within the mounted lifecycle hook:
mounted () {
this.$nextTick(() => {
var accessToken = this.$route.query.accessToken
this.fetchTeams(accessToken)
this.fetchRosters(accessToken)
})
}
The loop using forEach
doesn't seem to work as expected; it appears that the array is being treated as empty since the code inside the loop never executes. Additionally, if I log the array just before calling forEach
:
console.log(this.teamKeys)
console.log(JSON.stringify(this.teamKeys))
the second output displays an empty []
, while the first output in the console looks like this:
Array(2)
0: "371.l.215756.t.1"
1: "371.l.621475.t.2"
length: 2
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array
I'm convinced there's a simple mistake I'm making. Perhaps I overlooked something in creating the array? Or maybe my understanding of arrays needs revision?