vue-fetch lets you define and reuse fetch composables seamlessly within your Vue apps. Built on top of ofetch.
npm i @modernice/vue-fetchpnpm i @modernice/vue-fetchyarn add @modernice/vue-fetchNote: Make sure ofetch is also installed in your project as it is a peer-dependency of
vue-fetch.
- Define your fetch composable:
// composables/useFetch.ts
import { defineFetch, bearerAuth } from '@modernice/vue-fetch'
// Obtain your authentication token, for example, from @nuxtjs/auth
const authToken = ref('...')
export const useApi = defineFetch({
baseUrl: 'http://api.example.test',
headers: {}, // Set default headers for every request here
auth: bearerAuth(authToken), // Automatically adds "Authorization" header to every request
})- Use in any part of your app
// pages/foo.vue
<script setup>
const { fetch } = useApi()
const data = await fetch('/foo')
</script>