I have a dynamic list generated by api request via axios. In this list, I have an element's class that has to be generated after the is generated.
So here's what I have so far:
<template>
<div>
<div v-if="article_count > 0" class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>state</th>
<th>created at</th>
<th>headline</th>
</tr>
</thead>
<tbody>
<tr v-for="article in articles">
<td class="status">
<!-- the class of this element should change -->
<i class="fa fa-cog fa-spin fa-fw" v-bind:class="getArticleStatus(article.id)"></i>
</td>
<td>{{ article.created_at }}</td>
<td><strong>{{ article.headline }}</strong></td>
</tr>
</tbody>
</table>
</div>
<div v-else class="text-center">no articles found</div>
</div>
</template>
<script>
export default {
data() {
return {
article_count: 0,
articles: []
}
},
methods: {
// get the articles
getArticles() {
axios.get('/api/get_articles' )
.then((response) => {
this.article_count = response.data.article_count;
this.articles = response.data.articles;
})
},
// get the article's state
getArticleStatus(article_id) {
axios.get('/api/article_status/' + article_id)
.then((response) => {
switch(response.data) {
case 'ONL':
console.log('online'); // this works
return 'status online'; // this does not work...
case 'WAIT':
return 'status waiting';
case 'OFFL':
return 'status offline';
default:
return 'status unknown';
}
}).catch((error) => {
console.error(error);
})
}
},
mounted() {
this.getArticles()
}
}
</script>
As I can see in console (network tab), the api call to "/api/article_status/{article_id}" works, so the ajax call works. But the return statement does not reach v-bind:class...
As described in the comment, you can not bind Promise from the function to your element. What's more, there is a better alternative. You can use something like this.
methods: {
getArticles () {
axios.get(
'/api/get_articles'
).then(
response => {
this.article_count = response.data.article_count
this.articles = response.data.articles
}
)
},
getArticleState (id) {
axios.get(
'/api/article_status' + id,
).then(
response => {
this.articles.forEach(function (article) {
if(article.id === id){
switch(response.data) {
case 'ONL':
article.class = 'status waiting'
}
}
})
}
)
}
}
Now the only thing you need is bind the class like this:
<tr v-for="article in articles">
<i class='fa fa-cog' :class='article.class'>
</tr>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.