Issue
I have this code.
<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>
I want to write a function that receives as parameter an id for an author(from books.json), and returns the name of the author(from authors.json) I dont know how to write the function or how/where to use it. I'm working in vue, so it makes everything a little bit unclearly. Can someone help, please?
Solution
I'd use a computed property here instead. So make the calls as you are and remove the returnAuthorName
function.
The way these work, is as items
updates, this method will be called and return something.
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),
}))
},
}
Then in your template you'd have: book.author.name
, just loop through booksWithAuthor
instead of items.books
.
Answered By - Bill Criswell Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.