Mục tiêu:
Có 2 cách phổ biến:
Cách | Mô tả |
---|
fetch() | Hàm gốc của trình duyệt, không cần cài thêm |
axios | Thư viện chuyên dụng, dễ dùng hơn, hỗ trợ tốt hơn |
Demo: Lấy danh sách người dùng bằng fetch()
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Vue API Fetch</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<style>
body {
font-family: Arial;
padding: 20px;
}
.user {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="app">
<h2>📡 Danh sách người dùng từ API</h2>
<button @click="fetchUsers">🔄 Tải lại</button>
<p v-if="loading">⏳ Đang tải dữ liệu...</p>
<p v-if="error" style="color:red;">❌ Lỗi: {{ error }}</p>
<div v-for="user in users" :key="user.id" class="user">
<strong>{{ user.name }}</strong><br>
📧 {{ user.email }}<br>
🏢 {{ user.company.name }}
</div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
users: [],
loading: false,
error: null
};
},
methods: {
async fetchUsers() {
this.loading = true;
this.error = null;
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
if (!res.ok) throw new Error('Lỗi khi gọi API');
const data = await res.json();
this.users = data;
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
}
},
mounted() {
this.fetchUsers(); // Tự động gọi API khi trang load
}
}).mount('#app');
</script>
</body>
</html>
Giải thích nhanh:
Câu lệnh | Ý nghĩa |
---|
fetch(url) | Gửi yêu cầu đến API |
await res.json() | Chuyển dữ liệu JSON thành object |
mounted() | Hàm lifecycle, gọi khi component đã hiển thị |
Nếu dùng axios
:
- Thêm CDN vào
<head>
: <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- Đổi phần fetch như sau:
const res = await axios.get('https://jsonplaceholder.typicode.com/users'); this.users = res.data;
Bài tập thực hành:
- Lấy danh sách bài viết từ
https://jsonplaceholder.typicode.com/posts
- Hiển thị
title
và body
, mỗi bài trong 1 box
- Thêm bộ lọc tìm kiếm theo từ khóa
Kết luận:
Bạn đã biết:
- Cách lấy dữ liệu từ API trong Vue
- Cách dùng
fetch()
và axios
- Hiển thị danh sách người dùng thực tế
Thảo luận