Advertisement

Responsive Advertisement

Kapan menggunakan watch value dan watch getter - Vue 3

🧠 Perbedaan watch() vs Getter di Vue 3

Pertanyaan yang sering muncul saat menggunakan Vue 3: Kapan sebaiknya pakai watch(refVariable) langsung, dan kapan harus pakai getter () => source?


🎯 TL;DR:

Kasus Gunakan
ref atau reactive lokal watch(refVariable, ...) atau watch(() => reactiveVar.prop)
props watch(() => props.propName, ...)
computed atau getter watch(computedVar, ...)
Kasus kompleks / tidak yakin watch(() => sumber, ...) (lebih fleksibel)

✅ Contoh dan Penjelasan

1. Ref Biasa

const isOpen = ref(false);

watch(isOpen, (newVal) => {
  console.log("isOpen berubah", newVal);
});

2. Reactive Object (satu properti)

const state = reactive({ isOpen: false });

watch(() => state.isOpen, (newVal) => {
  console.log("state.isOpen berubah", newVal);
});

3. Props

const props = defineProps({ showModal: Boolean });

watch(() => props.showModal, (newVal) => {
  console.log("props berubah", newVal);
});

4. Computed

const total = computed(() => count.value * 2);

watch(total, (newVal) => {
  console.log("total berubah", newVal);
});

5. Kesalahan Umum

// ❌ Salah:
watch(() => someRef);

// ✅ Benar:
watch(someRef);

// ✅ Props:
watch(() => props.someProp);

📌 Kapan Harus Pakai Getter?

  • Saat mengawasi props
  • Saat mengawasi bagian dari reactive
  • Saat ingin memonitor derived value atau nested
  • Saat kombinasi nilai (misal: () => a.value + b.value)

💡 Bonus: Multiple Sources

watch([foo, bar], ([newFoo, newBar]) => {
  console.log(newFoo, newBar);
});

// Atau:
watch(() => [props.a, props.b], ([a, b]) => {
  console.log(a, b);
});


Posting Komentar

0 Komentar