我有这个代码。
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
},
returnAuthorName:function(authorId){
for(i in items.books)
_.find(items.authors, { 'id': items.books.authors });
return items.authors.name
}
}
};
</script>
<template>
<div id="app">
{{items.authors}}
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{items.authors.name}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td v-if="item.availability">Available</td>
<td v-else>Unavailable</td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
我想编写一个函数,该函数接收作者的ID(来自books.json)作为参数,并返回作者的名称(来自authors.json) 我不知道如何编写函数或如何/在哪里使用它。 我正在工作,所以一切都变得不清楚。 有人可以帮忙吗?
答案 0 :(得分:0)
我将在此处使用computed property。因此,请按原样进行呼叫,然后删除returnAuthorName
函数。
这些工作的方式是随着items
更新,此方法将被调用并返回某些内容。
computed: {
booksWithAuthor () {
const { books, authors } = this.items
// If we don't have both of these don't do anything...
if (books.length === 0 || authors.length === 0) {
return []
}
return books.map(book => ({
...book,
author: authors.find(author => author.id === book.authorId),
}))
},
}
然后在模板中您将拥有:book.author.name
,只需遍历booksWithAuthor
而不是items.books
。