In this section, we will explore how to create an Axios API request boilerplate in Vuejs. We will create a basic Vue.js application and make a request to an Axios endpoint that returns a list of products in the database with the structure for CRUD calling with Axios.
Installing Axios dependency
npm install axios
Custom Axios
In your ./src create axios.js file
import axios from "axios";
const http = axios.create({
baseURL: "http://127.0.0.1:8000/api",
headers: {
"Accept": "application/json"
}
});
export default http;
Create base service
In ./src create services folder and in services folder create BaseService.js that contain
import http from "@/axios";
export default class BaseService {
static get METHOD_GET() {
return 'GET';
}
static get METHOD_POST() {
return 'POST';
}
static get METHOD_PUT() {
return 'PUT';
}
static get METHOD_DELETE() {
return 'DELETE';
}
constructor(prefix) {
this.prefix = prefix;
}
index(data) {
return this.performRequest(BaseService.METHOD_GET, '', data);
}
show(id) {
return this.performRequest(BaseService.METHOD_GET, id);
}
store(data) {
return this.performRequest(BaseService.METHOD_POST, '', data);
}
update(id, data) {
return this.performRequest(BaseService.METHOD_PUT, id, data);
}
destroy(id) {
return this.performRequest(BaseService.METHOD_DELETE, id);
}
performRequest(method, url, data = {}, headers = {}) {
let endPoint = this.prefix + (url ? "/" + url : "");
let options = {
method,
url: endPoint,
data,
headers
};
options[method.toUpperCase() === BaseService.METHOD_GET ? "params" : "data"] = data;
return http(options);
}
}
After that let's say you want to request API related to product ProductService.js in the services folder
import BaseService from "./BaseService";
class ProductService extends BaseService {
constructor(prefix) {
super(prefix);
}
}
export default new ProductService('product');
How to call service?
In your component in getProduct() method is where you get the products list
<template>
<div>
<h5>Product</h5>
<div v-for="(product, index) in products.data" :key="index">
<span>Name: </span>
<span>{{ product.name }}</span>
</div>
</div>
</template>
<script>
import ProductService from "@/services/ProductService";
export default {
data() {
return {
products: {}
}
},
methods: {
getProduct() {
ProductService.index().then(res => {
this.products = res.data;
}).catch(e => {
console.log(e);
});
}
},
created() {
this.getProduct();
}
}
</script>
If you want to request other logic other than crud you can customize
import BaseService from "./BaseService";
class ProductService extends BaseService {
constructor(prefix) {
super(prefix);
}
custom(data) {
return this.performRequest(BaseService.METHOD_GET, 'url', data);
}
}
export default new ProductService('product');