gpt4 book ai didi

javascript - Vue.js : v-bind:class after axios request

转载 作者:行者123 更新时间:2023-12-03 02:52:47 25 4
gpt4 key购买 nike

我有一个由 api 请求通过 axios 生成的动态列表。在此列表中,我有一个元素的类,必须在生成后生成。

这就是我到目前为止所得到的:

<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>

正如我在控制台(网络选项卡)中看到的,对“/api/article_status/{article_id}”的 api 调用有效,因此 ajax 调用有效。但是return语句没有到达v-bind:class...

最佳答案

如评论中所述,您无法将函数中的 Promise 绑定(bind)到您的元素。更重要的是,还有更好的选择。你可以使用这样的东西。

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'
}
}
})
}
)
}

}

现在您唯一需要的就是像这样绑定(bind)类:

 <tr v-for="article in articles">
<i class='fa fa-cog' :class='article.class'>
</tr>

关于javascript - Vue.js : v-bind:class after axios request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com