Skip to content
Grok

Refactoring Vue Components (การปรับโครงสร้าง Component ใน Vue)

Composition API และการใช้ useXXX functions

การแยก logic ออกเป็นฟังก์ชันที่ reuse ได้เป็นวิธีที่ดีในการจัดการโค้ด Vue ที่ซับซ้อน

vue
<script setup lang="ts">
// สร้าง custom hook สำหรับ fetch ข้อมูล
const useFetchUser = (userId: string) => {
  const user = ref<User | null>(null);
  const loading = ref(false);
  const error = ref<Error | null>(null);

  const fetchData = async () => {
    try {
      loading.value = true;
      const response = await fetch(`/api/users/${userId}`);
      user.value = await response.json();
    } catch (err) {
      error.value = err as Error;
    } finally {
      loading.value = false;
    }
  };

  onMounted(fetchData);

  return { user, loading, error };
};
</script>

<template>
  <!-- ใช้งานใน component -->
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">Error: {{ error.message }}</div>
  <UserProfile v-else :user="user" />
</template>

เทคนิคการ Refactor

  1. แยก Logic ออกเป็น Custom Hooks (useXXX)
  2. ใช้ <script setup> เพื่อลด boilerplate
  3. ใช้ TypeScript เพื่อ type safety

การสร้าง Custom Hooks

Custom hooks ช่วยให้เราจัดการ logic ซ้ำๆ ในที่เดียว

การใช้ <script setup>

Syntax นี้ช่วยลด boilerplate และทำให้โค้ดอ่านง่ายขึ้น

Type Safety

การใช้ TypeScript ช่วยลดข้อผิดพลาดและเพิ่มความมั่นใจในโค้ด