I am running into an issue being able to initialize a value on App.vue to the result of a function when that function is async. I also tried setting it to the resolution of a promise but that didn't seem to work either. In the former case I just get an undefined value, and in the second I just get the ref type for a js promise. What is the proper way in Vue to initialize a variable to the result of a callback that will complete at a later time?
I prefer to do this in the created
lifecycle hook. Once the async action is complete, the result is stored in the data prop.
new Vue({
el: "#app",
data: {
asyncData: null
},
created() {
const url = 'https://jsonplaceholder.typicode.com/posts/1';
axios.get(url).then(response => {
this.asyncData = response.data;
});
}
})
Template:
<div id="app">
{{ asyncData }}
</div>