[[extend 'layout.html']]
<div id="myapp">
<select v-model="selected_book" v-on:change="update_reviews">
<option v-for="book in books" v-bind:value="book" v-text="book.title"></option>
</select>
<select v-model="selected_review">
<option v-for="review in reviews" v-bind:value="review" v-text="review.title"></option>
</select>
<p v-if="selected_review" v-text="selected_review.body"></p>
</div>
<script>
var app = {};
// get the base URL to call APIs
app.base_url = window.location.href.split("/").slice(0,4).join("/");
// store the app configuration
app.config = {};
// this function sets the initial state of the app
app.config.setup = function() {
// returns variables needed
return {
books: Vue.ref([]), // the list of books (as returned by API)
reviews: Vue.ref([]), // the list of reviews (as returned by API)
selected_book: Vue.ref(null), // the selected book
selected_review: Vue.ref(null) // the selected review
};
};
// methods available to the app
app.config.methods = {};
app.config.methods.update_books = function(){
// get books and store them in app.vue.books
fetch(app.base_url + "/books").then(r=>r.json()).then(data=>{app.vue.books=data.books;});
};
app.config.methods.update_reviews = function(){
// get reviews for selected_book_id and store them in app.vue.reviews
app.vue.selected_review = null;
fetch(app.base_url + "/reviews/" + app.vue.selected_book.id).then(r=>r.json()).then(data=>{app.vue.reviews=data.reviews;});
};
// build the app and link it with div#myapp
app.vue = Vue.createApp(app.config).mount("#myapp");
// populate the list of books
app.config.methods.update_books();
</script>