Composables: Vue 3'un Kalbi
Hala tum mantigi setup() icine yerlestiriyorsaniz veya karmasik bilesenler icin Options API kullaniyorsaniz, composables hayatinizi degistirecek. Bunlar, reaktif mantigi kapsulleyen ve bilesenler arasinda paylastirilabilen basit fonksiyonlardir.
// composables/useDebounce.js
import { ref, watch } from 'vue'
export function useDebounce(value, delay = 300) {
const debouncedValue = ref(value.value)
let timeout
watch(value, (newValue) => {
clearTimeout(timeout)
timeout = setTimeout(() => {
debouncedValue.value = newValue
}, delay)
})
return debouncedValue
}
// Usage in a component
const search = ref('')
const debouncedSearch = useDebounce(search, 500)
watch(debouncedSearch, (value) => {
fetchResults(value)
})
Daha Pratik Bir Composable: API Veri Cekme
// composables/useApi.js
import { ref, shallowRef } from 'vue'
export function useApi() {
const data = shallowRef(null)
const error = ref(null)
const loading = ref(false)
async function execute(url, options = {}) {
loading.value = true
error.value = null
try {
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options,
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
data.value = await response.json()
return data.value
} catch (e) {
error.value = e.message
throw e
} finally {
loading.value = false
}
}
return { data, error, loading, execute }
}
// Usage
const { data: users, loading, execute: fetchUsers } = useApi()
await fetchUsers('/api/users')
Provide/Inject: Prop Drilling'den Kurtulun
Veriyi birden fazla bilesen katmanindan gecirmeniz gerektiginde, provide ve inject prop drilling'e gore cok daha temiz bir cozumdur.
// In a parent component
import { provide, ref } from 'vue'
const currentTheme = ref('dark')
const toggleTheme = () => {
currentTheme.value = currentTheme.value === 'dark' ? 'light' : 'dark'
}
provide('theme', { currentTheme, toggleTheme })
// In any descendant (no matter how deep)
import { inject } from 'vue'
const { currentTheme, toggleTheme } = inject('theme')
Bilesenlerde v-model: Dogru Yontem
Vue 3'un defineModel makrosu (3.4+) ozel v-model destegini son derece kolaylastirir:
<!-- BaseInput.vue -->
<script setup>
const model = defineModel()
const props = defineProps({
label: String,
type: { type: String, default: 'text' },
})
</script>
<template>
<div class="form-group">
<label>{{ label }}</label>
<input :type="type" v-model="model" class="input" />
</div>
</template>
<!-- Usage -->
<BaseInput v-model="form.email" label="Email" type="email" />
Performans: Route'lari Lazy Loading ile Yukleyin
Tum uygulamanizi baslangiclta yuklemekten kacinin. Route bazinda ayirin:
// router/index.js
const routes = [
{
path: '/',
component: () => import('./views/Home.vue'),
},
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue'),
// Only loads when user navigates to /dashboard
},
{
path: '/settings',
component: () => import('./views/Settings.vue'),
},
]
Watcher'lar: Basit Durumlarda watchEffect Kullanin
// Instead of manually listing dependencies...
watch([firstName, lastName], ([first, last]) => {
fullName.value = `${first} ${last}`
})
// ...let Vue track them automatically
watchEffect(() => {
fullName.value = `${firstName.value} ${lastName.value}`
})
TypeScript ile Template Ref'leri
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const inputRef = ref<HTMLInputElement | null>(null)
onMounted(() => {
inputRef.value?.focus()
})
</script>
<template>
<input ref="inputRef" />
</template>
Hizli Ipuclari Ozeti
- Derin reaktiviteye ihtiyac duymayan buyuk nesneler icin
shallowRefkullanin — belirgin sekilde daha hizlidir - Template'lerde method yerine
computedtercih edin — computed degerleri onbellege alinir - Reaktif nesneleri destrukt ederken reaktiviteyi korumak icin
toRefskullanin v-fordongulerine dizi indeksleri yerine benzersiz ID'lerlekeynitelikleri ekleyin- Yukleme durumlari icin asenkron bilesenlerle birlikte
<Suspense>kullanin - Bilesenleri 200 satirin altinda tutun — daha uzunsa, bir composable veya alt bilesen cikartin
En iyi Vue kodu, arayuzun ne yaptigini tarif eder, nasil yaptigini degil. Composables "nasil" kismini halleder, bilesenler ise "ne" kismini tanimlar.