Upon initializing my component, I am attempting to load ajax data. However, I have noticed that this causes other items loaded via ajax in the created()
method to load synchronously rather than asynchronously. When this specific ajax request is triggered, it takes approximately 2 seconds to complete, resulting in everything else loading in a synchronous manner.
The first component, component1.vue, has a delay of about 2 seconds due to its ajax call:
export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
async created() {
this.balance = (await axios.get('/api/player/balance')).data
}
}
In contrast, the second component, component2.vue, loads much quicker from the ajax call:
export default {
data: () => {
return { items: [] }
},
async created() {
this.items = (await axios.get('/api/items')).data
}
}
Despite efforts, these components are not loading asynchronously as expected. The /api/player/balance
request is executed before the /api/items
request.
I tried using .then()
method as shown below:
export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
created() {
axios.get('/api/player/balance').then(function (response) {
this.balance = response.data
})
}
}
However, nesting this.balance = ...
within a setTimeout
resolved the issue with other items loaded properly.
Is there an alternative approach to handle this and ensure asynchronous loading of ajax requests?
Edit
Using fetch
successfully addressed the synchronous loading issue, enabling asynchronous loading of requests.
export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
async created() {
let response = await fetch('/api/player/balance')
this.balance = await response.json()
}
}
Can the same be achieved using axios
?