Part 2: GET
Requests (List Publishers)
To retrieve all publishers, we need to add another file ListPublishers.vue
under the component
folder and add the following code. This component calls two method (getAll()
, deleteAll()
) defined in src/services/PublisherDataService.js
.
getAll()
will invoke/api/publishers
endpoint with HTTP GET method:
getAll() { return http.get("/publishers"); }
deleteAll()
will invoke/api/publishers
endpoint with HTTP DELETE method:
deleteAll() { return http.delete(`/publishers`); }
Add this code to @@ListPublishers.vue@ file:
<template> <div class="list row"> <div class="col-md-6"> <h4>Publishers List</h4> <ul class="list-group"> <li class="list-group-item" :class="{ active: index == currentIndex }" v-for="(publisher, index) in publishers" :key="index" @click="setActivePublisher(publisher, index)" > {{ publisher.name }} </li> </ul> <br/> <button class="btn btn-outline-danger" @click="removeAllPublishers"> Remove All Publishers <i class="fa-solid fa-trash-can"></i> </button> <router-link to="/add" class="btn btn-primary">Add Publisher <i class="fa-solid fa-square-plus"></i></router-link> </div> <div class="col-md-6"> <div v-if="currentPublisher"> <!-- Card --> <div class="card"> <div class="card-header"> Publisher </div> <div class="card-body"> <h5 class="card-title">{{ currentPublisher.name }}</h5> <p class="card-text"><i class="fa-solid fa-location-dot"></i> {{ currentPublisher.publisher_address }}</p> <p class="card-text"><i class="fa-solid fa-address-book"></i> {{ currentPublisher.publisher_contact }}</p> <router-link :to="'/publishers/' + currentPublisher.id" class="btn btn-warning btn-sm">Edit <i class="fa-solid fa-pencil"></i></router-link> </div> </div> <!-- /Card --> </div> <div v-else> <br /> <div class="alert alert-info">Please click on a Publisher...!</div> </div> </div> </div> </template> <script> import PublisherDataService from "../services/PublisherDataService"; export default { name: "publisher-list", data() { return { publishers: [], currentPublisher: null, currentIndex: -1, name: "" }; }, methods: { retrievePublishers() { PublisherDataService.getAll() .then(response => { this.publishers = response.data; console.log(response.data); }) .catch(e => { console.log(e); }); }, refreshList() { this.retrievePublishers(); this.currentPublisher = null; this.currentIndex = -1; }, setActivePublisher(publisher, index) { this.currentPublisher = publisher; this.currentIndex = publisher ? index : -1; }, removeAllPublishers() { PublisherDataService.deleteAll() .then(response => { console.log(response.data); this.refreshList(); }) .catch(e => { console.log(e); }); }, }, mounted() { this.retrievePublishers(); } }; </script> <style> .list { text-align: left; max-width: 1200px; margin: auto; } </style>