Vue function that fetch resources asynchronously across the network.
type TUseFetchUrl = RequestInfo | Ref<RequestInfo>
function useFetch(
url: TUseFetchUrl,
options?: RequestInit,
runOnMount?: boolean
): {
data: Ref<any>
status: Ref<number | null>
statusText: Ref<string | null>
isLoading: Ref<boolean>
isFailed: Ref<boolean>
isAborted: Ref<boolean>
start: () => Promise<void>
stop: () => void
}
url: TUseFetchUrl
the fetch url value, can be type string or typeRequestInfo
.options: RequestInit
the fetch url options.runOnMount: boolean
whether to fetch on mount,true
by default.
data: Ref<any>
the response data, has to be of JSON type otherwise will return an errorstatus: Ref<number | null>
the status code of the responsestatusText: Ref<string | null>
the status text of the responseisLoading: Ref<boolean>
whether fetch request is loading or notisFailed: Ref<boolean>
whether fetch request has failed or notisAborted: Ref<boolean>
whether fetch request has been aborted or notstart: Function
the function used for starting fetch requeststop: Function
the function used for aborting fetch request
<template>
<div>
<div v-if="isFailed">Failed!</div>
<div v-else-if="isLoading">Loading...</div>
<div v-else-if="data">
<img :src="data.message" alt="" />
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import { useFetch } from 'vue-use-kit'
export default Vue.extend({
name: 'UseFetchDemo',
setup() {
const url = 'https://dog.ceo/api/breeds/image/random'
const { data, isLoading, isFailed } = useFetch(url)
return { data, isLoading, isFailed }
}
})
</script>