Reputation: 637
I'm trying to consume an API using axios.
This is my code until now:
<select>
<option v-for="value in values"> value.name </option>
</select>
// js
data(){
values: [],
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.value = res.data.dados;
console.log(res.data.dados);
})
.catch(error => {
console.log(error);
});
}
}
The promise's console.log
is working normally, but the options with data isn't rendered.
It's probably because my select component is being rendered before the 'getData()'. How can I fix it?
Upvotes: 1
Views: 3624
Reputation: 74
You've a typo on this.value
, it should be this.values
. If that doesn't work, use this.$forceUpdate()
to force re-render component
<select>
<option v-for="value in values">{{ value.name }}</option>
</select>
// js
data(){
values: [],
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.values = res.data.dados; // change value to values
console.log(res.data.dados);
this.$forceUpdate(); // add forceUpdate
})
.catch(error => {
console.log(error);
});
}
}
Upvotes: 1
Reputation: 639
Just put a loading handler.
<select v-if="loaded">
<option v-for="value in values"> value.name </option>
</select>
// js
data(){
values: [],
loaded: false,
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.value = res.data.dados;
this.loaded = true;
})
.catch(error => {
console.log(error);
this.loaded = true;
});
}
}
Upvotes: 2