import { ref, onMounted } from 'vue';
export function useApi(url) {
const data = ref(null);
const loading = ref(false);
const error = ref(null);
const fetchData = async () => {
loading.value = true;
error.value = null;
try {
const response = await fetch(url);
data.value = await response.json();
loading.value = false;
} catch (e) {
error.value = e;
loading.value = false;
}
};
onMounted(fetchData);
return { data, loading, error, fetchData };
}
<template>
<div>
<h1>Data Fetching Example</h1>
<div v-if="loading">Loading...</div>
<div v-if="error">Error: {{ error.message }}</div>
<pre v-if="data">{{ data }}</pre>
<button @click="fetchData">Refresh Data</button>
</div>
</template>
<script>
import { useApi } from './composables/useApi';
export default {
setup() {
const { data, loading, error, fetchData } = useApi('https://api.example.com/data');
return { data, loading, error, fetchData };
}
}
</script>