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?
Advertisement
Answer
I prefer to do this in the created
lifecycle hook. Once the async action is complete, the result is stored in the data prop.
JavaScript
x
13
13
1
new Vue({
2
el: "#app",
3
data: {
4
asyncData: null
5
},
6
created() {
7
const url = 'https://jsonplaceholder.typicode.com/posts/1';
8
axios.get(url).then(response => {
9
this.asyncData = response.data;
10
});
11
}
12
})
13
Template:
JavaScript
1
4
1
<div id="app">
2
{{ asyncData }}
3
</div>
4