Skip to content

INFO

Computed properties ใน Vue 3 ช่วยให้เราสามารถสร้างค่าที่คำนวณได้โดยอัตโนมัติเมื่อข้อมูลที่เกี่ยวข้องมีการเปลี่ยนแปลง

Basic Example

ตัวอย่างพื้นฐานของการใช้ computed property

vue
<template>
  <div>
    <p>Original message: "{{ message }}"</p>
    <p>Computed reversed message: "{{ reversedMessage }}"</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const message = ref('Hello')
const reversedMessage = computed(() => {
  return message.value.split('').reverse().join('')
})
</script>

Computed Caching vs. Methods

เปรียบเทียบระหว่าง computed property และ method

vue
<template>
  <div>
    <p>Computed: {{ computedValue }}</p>
    <p>Method: {{ methodValue() }}</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const count = ref(0)

// Computed property (cached)
const computedValue = computed(() => {
  console.log('Computing value...')
  return count.value * 2
})

// Method (not cached)
const methodValue = () => {
  console.log('Calculating value...')
  return count.value * 2
}

// Increase count every second
setInterval(() => {
  count.value++
}, 1000)
</script>

Writable Computed

ตัวอย่างการสร้าง computed property ที่สามารถเขียนค่าได้

vue
<template>
  <div>
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
    <p>Full Name: {{ fullName }}</p>
    <input v-model="fullName">
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

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

const fullName = computed({
  get() {
    return `${firstName.value} ${lastName.value}`
  },
  set(newValue) {
    [firstName.value, lastName.value] = newValue.split(' ')
  }
})
</script>

Best Practices

แนวทางปฏิบัติที่ดีในการใช้ computed properties

  1. ใช้ computed properties สำหรับการคำนวณที่ซับซ้อนหรือใช้ซ้ำบ่อยๆ:
vue
<script setup>
import { ref, computed } from 'vue'

const items = ref([
  { id: 1, name: 'Apple', price: 0.5, quantity: 3 },
  { id: 2, name: 'Banana', price: 0.3, quantity: 5 },
  { id: 3, name: 'Cherry', price: 0.8, quantity: 2 }
])

const total = computed(() => {
  return items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})
</script>
  1. หลีกเลี่ยงการเปลี่ยนแปลงข้อมูลภายใน getter ของ computed property:
vue
// ไม่ควรทำแบบนี้
const badComputed = computed(() => {
  someState.value++ // มีการเปลี่ยนแปลง state
  return someState.value
})

// ควรทำแบบนี้
const goodComputed = computed(() => {
  return someState.value + 1
})
  1. ใช้ computed properties แทนการใช้ methods เมื่อต้องการ caching:
vue
// ใช้ computed property เมื่อต้องการ caching
const cachedValue = computed(() => {
  return expensiveOperation()
})

// ใช้ method เมื่อไม่ต้องการ caching หรือต้องการส่ง parameters
const nonCachedValue = () => {
  return expensiveOperation()
}

Released under the MIT License