简介
响应式的 Fetch API 提供了取消请求的能力,在请求发出前拦截请求,当 url 改变时自动重新发出请求,并且创建自定义配置项的 useFetch 。
用法
基础用法
useFetch 函数可以直接接收一个 url 。url 可以是 string 或者 ref 对象。data 对象包含了请求的结果,error 对象包含了所有的错误,isFetching对象可以表明请求是否在加载中。
import { useFetch } from '@vueuse/core'
const { isFetching, error, data } = useFetch(url)
异步用法
useFetch 可以像普通 fetch 那样使用 await 语法糖。注意,只要组件是异步的,使用该组件的时候需用 <Suspense> 标签进行包裹。
import { useFetch } from '@vueuse/core'
const { isFetching, error, data } = await useFetch(url)
URL改变时候重新请求
使用 ref 包裹 url 参数,可以让 useFetch 函数在 url 改变的时候自动触发另一个请求。
const url = ref('https://my-api.com/user/1')
const { data } = useFetch(url, { refetch: true })
url.value = 'https://my-api.com/user/2' // Will trigger another request
阻止请求立刻发送
将 immediate 配置项设置为 false,便可以阻止请求的发送,调用immediate函数便可继续发送请求。
const { execute } = useFetch(url, { immediate: false })
execute()
中止请求
从 useFetch 函数返回值中解构出来的 abort 函数可以中止请求。canAbort属性表明该请求是否可以被中止。
const { abort, canAbort } = useFetch(url)
setTimeout(() => {
if (canAbort.value)
abort()
}, 100)
使用 timeout 属性可以实现自动中止请求。当计时器结束时调用 abort 函数。
const { data } = useFetch(url, { timeout: 100 })
拦截请求
beforeFetch 配置项可以在请求发送和修改请求配置项与url之前拦截它。
const { data } = useFetch(url, {
async beforeFetch({ url, options, cancel }) {
const myToken = await getMyToken()
if (!myToken)
cancel()
options.headers = {
...options.headers,
Authorization: `Bearer ${myToken}`,
}
return {
options,
}
},
})
afterFetch 配置项可以在响应数据更新之前拦截它。
const { data } = useFetch(url, {
afterFetch(ctx) {
if (ctx.data.title === 'HxH')
ctx.data.title = 'Hunter x Hunter' // Modifies the response data
return ctx
},
})
onFetchError 配置项可以在响应数据和错误更新之前拦截它们。
const { data } = useFetch(url, {
onFetchError(ctx) {
// ctx.data can be null when 5xx response
if (ctx.data === null)
ctx.data = { title: 'Hunter x Hunter' } // Modifies the response data
ctx.error = new Error('Custom Error') // Modifies the error
return ctx
},
})
设置请求方法和返回类型
可以通过在useFetch的末尾添加适当的方法来设置请求方法和返回类型。
// Request will be sent with GET method and data will be parsed as JSON
const { data } = useFetch(url).get().json()
// Request will be sent with POST method and data will be parsed as text
const { data } = useFetch(url).post().text()
// Or set the method using the options
// Request will be sent with GET method and data will be parsed as blob
const { data } = useFetch(url, { method: 'GET' }, { refetch: true }).blob()
创建自定义实例
createFetch 函数返回一个带有用户传入的配置项的 useFetch 函数。便于在使用相同 baseURL 或需要 Authorization headers 的应用程序中与API交互。
const useMyFetch = createFetch({
baseUrl: 'https://my-api.com',
options: {
async beforeFetch({ options }) {
const myToken = await getMyToken()
options.headers.Authorization = `Bearer ${myToken}`
return { options }
},
},
fetchOptions: {
mode: 'cors',
},
})
const { isFetching, error, data } = useMyFetch('users')
事件
onFetchResponse 和 onFetchError 将分别在获取请求响应和错误时触发。
const { onFetchResponse, onFetchError } = useFetch(url)
onFetchResponse((response) => {
console.log(response.status)
})
onFetchError((error) => {
console.error(error.message)
})