design

Vue.js Composition API: Daha Modüler ve Esnek Bileşenler

March 21, 2025

Composition API Nedir?

Composition API, Vue.js bileşenlerinin mantığını fonksiyonlar ve reaktif değişkenler kullanarak organize etmenizi sağlar. Options API'deki datamethodscomputed

watch gibi seçenekler yerine, tüm mantığı bir setup fonksiyonu içinde yazabilirsiniz

. Bu, özellikle büyük ve karmaşık bileşenlerde kodun daha iyi organize edilmesine olanak tanır.

Composition API'nin Avantajları

  1. Daha İyi Kod Organizasyonu: İlgili kodları bir arada gruplayarak daha okunabilir ve sürdürülebilir bir yapı sunar.
  2. Yeniden Kullanılabilir Logic: Logic'i fonksiyonlar halinde yazıp farklı bileşenlerde tekrar kullanabilirsiniz.
  3. TypeScript Desteği: Composition API, TypeScript ile daha iyi entegre olur.
  4. Daha Esnek Yapı: Options API'deki sınırlamaları ortadan kaldırır ve daha dinamik bir geliştirme deneyimi sunar.

Composition API Temelleri

1. setup Fonksiyonu

Composition API'nin kalbinde setup fonksiyonu bulunur. Bu fonksiyon, bileşenin başlangıç noktasıdır ve bileşenin mantığını burada yazarsınız.

Vue Dosyası

index.vue

js
<template>
  <div>
    <p>{{ message }}</p>
    <button @click="updateMessage">Mesajı Güncelle</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    // Reaktif bir değişken oluşturma
    const message = ref('Merhaba Vue.js!');

    // Fonksiyon tanımlama
    function updateMessage() {
      message.value = 'Mesaj güncellendi!';
    }

    // Template'e gönderilecek değerler
    return {
      message,
      updateMessage,
    };
  },
};
</script> 
  • ref: Reaktif bir değişken oluşturmak için kullanılır. .value ile değerine erişilir.
  • setup: Bileşenin mantığını yazdığınız fonksiyon. Template'e gönderilecek değerleri return eder.

2. Reaktif Veriler (ref ve reactive)

Composition API'de reaktif veriler oluşturmak için ref ve reactive kullanılır.

ref Kullanımı:


Vue Dosyası

index.vue

js
import { ref } from 'vue';

const count = ref(0); // Başlangıç değeri 0
console.log(count.value); // Değere erişmek için .value kullanılır 

reactive Kullanımı:


Vue Dosyası

index.vue

js
import { reactive } from 'vue';

const state = reactive({
  name: 'Vue.js',
  version: 3,
});
console.log(state.name); // Değere doğrudan erişilir 

3. Computed Özellikler

Composition API'de computed özellikler oluşturmak için computed fonksiyonu kullanılır.

Vue Dosyası

index.vue

js
import { ref, computed } from 'vue';

const count = ref(0);
const doubleCount = computed(() => count.value * 2);

console.log(doubleCount.value); // 0 

4. Watchers (watch ve watchEffect)

Değişiklikleri izlemek için watch ve watchEffect kullanılır.

watch Kullanımı:


Vue Dosyası

index.vue

js
import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`Count değişti: ${oldValue} -> ${newValue}`);
}); 

watchEffect Kullanımı:


Vue Dosyası

index.vue

js
import { ref, watchEffect } from 'vue';

const count = ref(0);

watchEffect(() => {
  console.log(`Count değeri: ${count.value}`);
}); 

5. Lifecycle Hooks

Composition API'de lifecycle hook'ları (onMountedonUpdatedonUnmounted vb.) doğrudan kullanılır.

Vue Dosyası

index.vue

js
mport { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  console.log('Bileşen oluşturuldu');
});

onUnmounted(() => {
  console.log('Bileşen kaldırıldı');
}); 

Composition API ile Yeniden Kullanılabilir Logic

Composition API'nin en güçlü yanlarından biri, logic'i composable functions olarak yazıp farklı bileşenlerde tekrar kullanabilmenizdir.

Örnek: Bir Counter Composable'ı


Vue Dosyası

index.vue

js
// useCounter.js
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);

  function increment() {
    count.value++;
  }

  function decrement() {
    count.value--;
  }

  return {
    count,
    increment,
    decrement,
  };
} 

Bileşende Kullanım:




Vue Dosyası

index.vue

js
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Arttır</button>
    <button @click="decrement">Azalt</button>
  </div>
</template>

<script>
import { useCounter } from './useCounter';

export default {
  setup() {
    const { count, increment, decrement } = useCounter();

    return {
      count,
      increment,
      decrement,
    };
  },
};
</script> 

Composition API vs Options API


ÖzellikComposition APIOptions APIKod Organizasyonuİlgili kodlar bir arada gruplanır.datamethodscomputed ayrıdır.Yeniden KullanımLogic, composable fonksiyonlarla paylaşılır.Mixins veya scoped slots kullanılır.TypeScript DesteğiDaha iyi entegrasyon.Daha az destek.Öğrenme EğrisiBiraz daha dik.Daha kolay ve anlaşılır.Sonuç

Vue.js Composition API, özellikle büyük ve karmaşık uygulamalarda kodun daha modüler ve yeniden kullanılabilir olmasını sağlar. setup fonksiyonu, refreactivecomputedwatch gibi özelliklerle geliştirme sürecinizi daha esnek ve güçlü hale getirir. Eğer Vue.js ile modern ve sürdürülebilir uygulamalar geliştirmek istiyorsanız, Composition API'yi öğrenmek ve kullanmak oldukça faydalı olacaktır.

Composition API'yi projelerinize entegre ederek, hem geliştirme hızınızı artırabilir hem de daha temiz bir kod yapısı oluşturabilirsiniz. 🚀

1 + 1 =