0👍
The fetch function is asynchronous and you are not waiting for the getData function to resolve before calling otherFunction.
Wait for the promise to resolve before calling other functions that depends on the data:
const app = Vue.createApp({
data() {
return {
dataAll: [],
};
},
mounted() {
this.getData().then(() => {
this.otherFunction();
})
},
methods: {
getData() {
return fetch('app/api.php')
.then((response) => response.json())
.then((data) => {
this.dataAll = data;
});
},
otherFunction() {
console.log(this.dataAll);
}
}
});
Or you can also use async await
const app = Vue.createApp({
data() {
return {
dataAll: [],
};
},
async mounted() {
await this.getData();
this.otherFunction();
},
methods: {
async getData() {
const data = await fetch(
"app/api.php"
).then((response) => response.json());
this.dataAll = data;
},
otherFunction() {
console.log(this.dataAll);
}
}
});
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#using_the_fetch_api
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await
- [Vuejs]-V-model keeps showing the same data in vuejs
- [Vuejs]-When refreshing, it returning The resource you are looking for has been removed, had its name changed, or is temporarily unavailable
Source:stackexchange.com