Skip to content

Computed Properties (computed)

คืออะไร?

computed คือฟีเจอร์ของ Vue ที่ใช้สำหรับสร้างค่าที่คำนวณได้ (derived state) จาก state อื่น ๆ โดยอัตโนมัติ เมื่อ state ที่เกี่ยวข้องเปลี่ยนแปลง ค่า computed ก็จะอัปเดตตามทันที

  • เหมาะกับกรณีที่ต้องการแสดงผล/ใช้ค่าที่ต้องคำนวณจาก state หลายตัว
  • มีการ cache อัตโนมัติ: ถ้า state ไม่เปลี่ยน ค่า computed ก็จะไม่คำนวณใหม่

ตัวอย่าง (Composition API)

ts
<script setup lang="ts">
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

const fullName = computed(() => `${firstName.value} ${lastName.value}`)
</script>

<template>
  <div>{{ fullName }}</div>
</template>

จุดเด่นของ computed

  • ใช้เหมือน property ทั่วไปใน template หรือ script
  • Cache อัตโนมัติ: ไม่คำนวณซ้ำถ้า dependency ไม่เปลี่ยน
  • เหมาะกับ logic ที่เป็น pure function (input เดียว output เดียว)

เมื่อไหร่ควรใช้ computed?

  • เมื่อค่าที่ต้องการขึ้นกับ state อื่น ๆ และต้องการให้คำนวณใหม่อัตโนมัติ
  • ไม่ต้องการ side effect (ไม่ควรใช้ computed เพื่อ trigger อะไร)

เปรียบเทียบกับ watch/watchers

computedwatch/watchers
ใช้สำหรับคำนวณค่าใหม่จาก stateใช้สำหรับ "เฝ้าดู" การเปลี่ยนแปลงของ state เพื่อ run logic (side effect)
มี cache อัตโนมัติไม่มี cache
เหมาะกับ logic ที่ไม่มี side effectเหมาะกับ logic ที่มี side effect เช่น fetch, log, ฯลฯ
ใช้เหมือน propertyต้องกำหนด callback function

ข้อควรระวัง

  • อย่าใช้ computed เพื่อทำ side effect เช่น call API หรือเปลี่ยน state อื่น
  • ถ้า logic มี side effect ให้ใช้ watch แทน

สรุป

computed คือเครื่องมือสำหรับสร้างค่าที่คำนวณได้ใน Vue ที่ใช้ง่ายและปลอดภัยจาก side effect ถ้าอยาก "ดู" state แล้ว "ทำอะไร" ให้ใช้ watch แทน