Composables are functions that encapsulate reusable logic. They can be imported and used across multiple components, making your code more modular. Composables allow you to share state, methods, computed properties, and watchers across different parts of your application.
// useFetch.js
import { ref, onMounted } from ‘vue’;
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const fetchData = async () => {
try {
const response = await fetch(url);
data.value = await response.json();
} catch (err) {
error.value = err;
}
};
onMounted(fetchData);
return { data, error };
}
<template>
<div>
<div v-if=”error”>Error: {{ error.message }}</div>
<div v-else-if=”data”>
<pre>{{ data }}</pre>
</div>
</div>
</template>
<script>
import { useFetch } from ‘./useFetch’;
export default {
setup() {
const { data, error } = useFetch(‘https://api.example.com/data’);
return { data, error };
}
};
</script>