Đăng nhập

BÀI 11: KẾT NỐI API TRONG VUE 3 (VỚI FETCH VÀ AXIOS)

Mục tiêu:

Có 2 cách phổ biến:

CáchMô tả
fetch()Hàm gốc của trình duyệt, không cần cài thêm
axiosThư 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:

  1. Thêm CDN vào <head>: <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  2. Đổ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:

  1. Lấy danh sách bài viết từ https://jsonplaceholder.typicode.com/posts
  2. Hiển thị titlebody, mỗi bài trong 1 box
  3. 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()axios
  • Hiển thị danh sách người dùng thực tế

Thảo luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Đăng ký nhận tin mới

Nhận bài học, tài nguyên và cơ hội việc làm qua email hàng tuần.

Chúng tôi cam kết không spam. Bạn có thể hủy bất cứ lúc nào.