Composition API tổ chức logic theo chức năng bằng ref, reactive, computed, watch và các hook vòng đời. Bài này dùng Composition API để gọi API, xử lý trạng thái đang tải, lỗi và tách logic thành composable dùng lại.

60 phútTrung cấp
Bạn sẽ học được
  • ref và reactive
  • computed, watch trong script setup
  • onMounted gọi API bằng fetch
  • Viết composable dùng lại

ref và reactive

import { ref, reactive, computed } from "vue";
const dem = ref(0);          // dùng dem.value trong script
const sv = reactive({ ten: "Lan", diem: 9 });
const dat = computed(() => sv.diem >= 5);

Trong template không cần .value.

Gọi API

<script setup>
import { ref, onMounted } from "vue";
const ds = ref([]), dangTai = ref(true), loi = ref("");

onMounted(async () => {
  try {
    const r = await fetch("https://jsonplaceholder.typicode.com/users");
    if (!r.ok) throw new Error("Lỗi " + r.status);
    ds.value = await r.json();
  } catch (e) { loi.value = e.message; }
  finally { dangTai.value = false; }
});
</script>

<template>
  <p v-if="dangTai">Đang tải...</p>
  <p v-else-if="loi">{{ loi }}</p>
  <ul v-else><li v-for="u in ds" :key="u.id">{{ u.name }}</li></ul>
</template>

Composable

// src/composables/useFetch.js
import { ref } from "vue";
export function useFetch(url) {
  const data = ref(null), error = ref(null);
  fetch(url).then(r => r.json()).then(d => data.value = d).catch(e => error.value = e);
  return { data, error };
}
Mẹo hay

Hook vòng đời thường dùng: onMounted (sau khi hiển thị), onUnmounted (dọn dẹp hẹn giờ, sự kiện).

Thực hành
  1. Hiển thị danh sách người dùng từ API.
  2. Thêm ô tìm kiếm lọc theo tên bằng computed.
  3. Tách logic gọi API thành composable useFetch.
Tóm tắt bài học
  • ref cho giá trị đơn, reactive cho đối tượng.
  • onMounted là nơi gọi API ban đầu.
  • Composable giúp tái sử dụng logic.