1👍
I agree with Decade Moon that your first approach is the better way to do it (though you could use created
instead of mounted
).
The reason your second approach doesn’t work is that you return an array and then replace the local variable’s value with a different array. What you need to do is populate the array you returned.
new Vue({
el: '#app',
data() {
return {item: this.getItem()}
},
methods: {
getItem() {
let val = [];
setTimeout(() => {
const result = ['first','second','third'];
val.push(...result);
}, 800);
return val;
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">{{item}}</div>
2👍
Your first code snippet is the correct way to do it.
You can’t initialize domains
with the data from the API response because it is an async operation which may or may not be resolved successfully at some point in the future, well after the component is mounted. You might also want to do other things like keeping track of the async operation with a loading
property which you set to true
for the duration of the request.
Your component will initially be in a loading state which does not yet have any domains
data, and you need to account for this. Show a loading spinner or something during this time.
1👍
I might be deviating slightly from the question (since it explicitly mentions the data
property), but I think this might be helpful. Personally, if I want to provide some data with more complex logic I use the computed
property. This is great in my opinion and you can read more about it in the docs. The problem in this case is that it doesn’t work entirely as expected with asynchronous operations…
However, there is a lovely little module called vue-async-computed which can be found here. It solves this specific problem by providing an asyncComputed
property and keeps the code really clean!