引言 在 Vue3 项目里,几乎每个页面都要和异步请求打交道:调接口拿数据、展示 loading、处理错误、组件卸载后还要防止状态回写。如果每次都在组件里手写 loading = true / try / await / catch / finally,不仅重复,还容易踩竞态的坑——先发出的慢请求后返回,把后发出的快请求结果覆盖掉,页面就显示出错乱的数据。
组合式函数(Composable)是 Vue3 推荐的复用逻辑方式。本文我们从零封装一个 useRequest,把 data / error / loading 三件套和「竞态保护 + 可选缓存」一次性解决,并在文末给出可直接在浏览器打开运行的完整示例。
原理 useRequest 的核心是一个返回响应式状态的对象,它把请求动作收敛成唯一的 run() 方法。两个关键技术点:
竞态保护。用一个自增的 requestId 标记每一次请求。请求完成时,只有当自己的 id 等于「当前最新请求 id」时才允许写入 data 和 loading。这样即使慢请求后到,也因为 id 过期而被丢弃,最终结果永远是最新一次请求。
可选缓存。当传入 cacheKey 时,把成功结果按 key 存入一个模块级 Map,并设置存活时间 cacheTime。下次命中且未过期时直接复用,跳过网络请求。
它不依赖任何请求库,传入的 fetcher 只是一个返回 Promise 的函数,因此可以搭配 fetch、axios 或任意封装。
代码实现 先写好 Hook 本体(ESM 写法,配合 <script setup> 或任何 setup 函数):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 import { ref } from 'vue' const cache = new Map ()export function useRequest (fetcher, options = {} ) { const { cacheKey, cacheTime = 5 * 60 * 1000 , immediate = false } = options const data = ref (null ) const error = ref (null ) const loading = ref (false ) let requestId = 0 async function run (...args ) { if (cacheKey) { const hit = cache.get (cacheKey) if (hit && Date .now () - hit.time < cacheTime) { data.value = hit.data return hit.data } } const id = ++requestId loading.value = true error.value = null try { const res = await fetcher (...args) if (id !== requestId) return data.value = res if (cacheKey) cache.set (cacheKey, { data : res, time : Date .now () }) return res } catch (e) { if (id !== requestId) return error.value = e throw e } finally { if (id === requestId) loading.value = false } } if (immediate) run () return { data, error, loading, run } }
在组件里使用非常简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { useRequest } from '@/composables/useRequest' export default { setup ( ) { const fetchUser = (id ) => fetch (`/api/user/${id} ` ).then ((r ) => r.json ()) const { data, error, loading, run } = useRequest (fetchUser, { cacheKey : 'user-detail' , cacheTime : 60000 , }) return { data, error, loading, load : (id ) => run (id) } }, }
下方是完整可运行示例,保存为 .html 用浏览器打开即可验证竞态保护:先后点击「慢请求」和「快请求」,最终页面只保留快请求结果,慢请求被自动丢弃。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 <!DOCTYPE html > <html lang ="zh-CN" > <head > <meta charset ="UTF-8" /> <title > useRequest 竞态演示</title > <script src ="https://unpkg.com/vue@3/dist/vue.global.prod.js" > </script > <style > body { font-family : system-ui; padding : 24px ; } .card { border : 1px solid #ddd ; padding : 16px ; border-radius : 8px ; max-width : 520px ; } button { margin-right : 8px ; padding : 6px 12px ; } .muted { color : #888 ; font-size : 13px ; } </style > </head > <body > <div id ="app" > <div class ="card" > <p > 当前结果:<b > {{ data ?? '(空)' }}</b > </p > <p class ="muted" > loading: {{ loading }} | 累计点击: {{ seq }}</p > <button @click ="slow" > 发慢请求(800ms)</button > <button @click ="fast" > 再发快请求(200ms)</button > <p class ="muted" > 先点慢请求、再点快请求:快请求先返回,慢请求后到却被丢弃,结果始终是快请求。</p > </div > </div > <script > const { createApp, ref } = Vue const cache = new Map () function useRequest (fetcher, options = {} ) { const { cacheKey, cacheTime = 300000 , immediate = false } = options const data = ref (null ) const error = ref (null ) const loading = ref (false ) let requestId = 0 async function run (...args ) { if (cacheKey) { const hit = cache.get (cacheKey) if (hit && Date .now () - hit.time < cacheTime) { data.value = hit.data ; return hit.data } } const id = ++requestId loading.value = true error.value = null try { const res = await fetcher (...args) if (id !== requestId) return data.value = res if (cacheKey) cache.set (cacheKey, { data : res, time : Date .now () }) return res } catch (e) { if (id !== requestId) return error.value = e } finally { if (id === requestId) loading.value = false } } if (immediate) run () return { data, error, loading, run } } function mockApi (text, delay ) { return new Promise ((r ) => setTimeout (() => r (text), delay)) } createApp ({ setup ( ) { const { data, loading, run } = useRequest ( (text, delay ) => mockApi (text, delay) ) const seq = ref (0 ) const slow = ( ) => { seq.value ++; run ('慢请求结果' , 800 ) } const fast = ( ) => { seq.value ++; run ('快请求结果' , 200 ) } return { data, loading, seq, slow, fast } }, }).mount ('#app' ) </script > </body > </html >
常见坑
直接把 run 解构成多个 ref 后,不要在模板里把 run 当普通函数反复 new 调用。每次 run 都自增 requestId,保证了写回收敛,但如果传入的 fetcher 自身会发起多个并发子请求,requestId 只拦最外层,内层需各自处理。
缓存是模块级共享的,多个组件用相同 cacheKey 会互相读取。跨页面共享数据有时是优点,但若数据带用户态,请用「用户 id + key」拼接,避免串号。
cacheTime 用绝对时间戳判断,组件卸载不会自动清缓存。长时间驻留的页面若数据易变,要么缩短 cacheTime,要么在关键操作后用 cache.delete(cacheKey) 手动失效。
不要把 immediate: true 和依赖路由参数的请求混用,参数变化不会自动重新请求,应改为 watch 参数后手动 run()。
小结 一个不到 50 行的 useRequest,就帮我们统一了异步请求的 loading、错误、竞态与缓存逻辑。它遵循 Vue3 组合式函数「接收响应式输入、返回响应式状态」的约定,可无缝接入 Composition API。当你把这类通用能力沉淀成 Composable,业务组件就能真正只关心「拿到数据后怎么渲染」,而不是反复搬运样板代码。