Composables — reusable logic.
useFetch:
1// composables/useFetch.ts2import { ref, watchEffect } from "vue"34export function useFetch(url) {5 const data = ref(null)6 const error = ref(null)7 const loading = ref(true)89 watchEffect(async () => {10 try {11 data.value = await fetch(url).then(r => r.json())12 } catch (e) {13 error.value = e14 } finally {15 loading.value = false16 }17 })1819 return { data, error, loading }20}
Usage:
1<script setup>2import { useFetch } from "@/composables/useFetch"34const { data, loading } = useFetch("/api/users")5</script>
Key: Composables for reusable logic.