Để xây dựng ứng dụng Vue 3 giao tiếp với backend, Axios là thư viện HTTP client phổ biến và hiệu quả. Bài viết này hướng dẫn cách cài đặt, sử dụng cơ bản, đóng gói hàm và áp dụng interceptor để tối ưu hóa việc gọi API.
Cài đặt dự án Vue 3
Sử dụng Vite để khởi tạo dự án mới:
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install
npm run dev
Cài đặt và cấu hình Axios
Cài đặt Axios qua npm:
npm install axios
Khái niệm Axios
Axios là thư viện HTTP client dựa trên Promise, hoạt động đồng nhất giữa trình duyệt và Node.js. Nó hỗ trợ xử lý request/response, tự động chuyển đổi JSON và có thể hủy request.
Gửi yêu cầu GET
import axios from 'axios';
// Cách 1: Truyền tham số trực tiếp trong URL
axios.get('/api/user?userId=100')
.then(res => console.log(res.data))
.catch(err => console.error(err));
// Cách 2: Sử dụng params object
axios.get('/api/user', {
params: { userId: 100 }
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
Ví dụ tích hợp trong component Vue
Component ArticleList.vue:
<template>
<div>
Danh mục: <input v-model="filters.category" />
Trạng thái: <input v-model="filters.status" />
<button @click="fetchArticles">Tìm kiếm</button>
<table border="1">
<thead>
<tr>
<th>Tiêu đề</th>
<th>Danh mục</th>
<th>Ngày đăng</th>
<th>Trạng thái</th>
</tr>
</thead>
<tbody>
<tr v-for="item in articles" :key="item.id">
<td>{{ item.title }}</td>
<td>{{ item.category }}</td>
<td>{{ item.publishedAt }}</td>
<td>{{ item.status }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { fetchAllArticles, searchArticles } from '@/services/articleService';
const articles = ref([]);
const filters = ref({ category: '', status: '' });
onMounted(async () => {
articles.value = await fetchAllArticles();
});
const fetchArticles = async () => {
articles.value = await searchArticles(filters.value);
};
</script>
Đóng gói service API
Tạo file src/services/articleService.js:
import apiClient from '@/utils/apiClient';
export const fetchAllArticles = async () => {
const response = await apiClient.get('/articles');
return response.data;
};
export const searchArticles = async (params) => {
const response = await apiClient.get('/articles/search', { params });
return response.data;
};
Cấu hình base URL và Interceptor
Tạo file src/utils/apiClient.js:
import axios from 'axios';
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
timeout: 10000,
});
// Interceptor xử lý response
apiClient.interceptors.response.use(
(response) => response.data,
(error) => {
console.error('API Error:', error);
return Promise.reject(error);
}
);
export default apiClient;
Thêm biến môi trường
Tạo file .env ở gốc dự án:
VITE_API_BASE_URL=http://localhost:8080
Với cách cấu trúc này, bạn có thể dễ dàng:
- Thay đổi endpoint API mà không cần sửa nhiều file
- Xử lý lỗi tập trung qua interceptor
- Tái sử dụng service trong nhiều component
- Dễ dàng mock API trong quá trình phát triển