Install Axios
npm install axios
Create an API service
Instead of importing Axios in every component, create a reusable instance.
// src/services/api.js
import axios from "axios";
const api = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
"Content-Type": "application/json",
},
});
export default api;
Use in a component (Composition API)
<template>
<div>
<button @click="fetchUsers">Load Users</button>
<div v-for="user in users" :key="user.id">
<h3></h3>
<p></p>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import api from "@/services/api";
const users = ref([]);
async function fetchUsers() {
const { data } = await api.get("/users");
users = data;
}
</script>
Composable for reusable fetch logic
// src/composables/useApi.js
import { ref } from "vue";
import api from "@/services/api";
export function useApi(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(false);
async function fetch() {
loading.value = true;
try {
const res = await api.get(url);
data.value = res.data;
} catch (e) {
error.value = e;
} finally {
loading.value = false;
}
}
return { data, error, loading, fetch };
}
<script setup>
import { useApi } from "@/composables/useApi";
const { data: users, loading, fetch: loadUsers } = useApi("/users");
</script>
Interceptors
Add request/response interceptors for auth tokens or error handling.
// src/services/api.js
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// handle unauthorized
}
return Promise.reject(error);
}
);