【发布时间】:2021-10-05 04:41:33
【问题描述】:
我有一个获取书籍列表的 API,在每本书中我都有作者 ID。 我还想通过另一个 API(获取作者)从该 ID 获取作者姓名,所以我使用 v-for 来获取书籍列表中的项目。我调用 getAuthor(authorId) 函数的每个项目,但它会无限重复。有谁知道是什么原因? 我的源代码:
export default {
name: 'GetBooks',
data() {
return {
books: [],
categories: [],
author: [],
};
},
created()
{
this.getBooks();
},
methods: {
getBooks() {
BookServices.getBooks().then(response => {
this.books = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
},
getAuthor(id) {
BookServices.getAuthor(id).then(response => {
this.author = response.data.name;
console.log(response.data.name);
});
return this.author;
},
}
与:
<tbody>
<tr v-for="item in books" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ getAuthor(item.authorId) }}</td>
<td>{{ item.price }}</td>
<td>{{ item.year }}</td>
<td><input class='myclass' type='button' value='Detail'/></td>
</tr>
</tbody>
【问题讨论】:
标签: javascript vue.js vuejs2 v-for