1
1
import {
2
+ ref ,
2
3
isRef ,
3
4
onBeforeMount ,
4
5
onServerPrefetch ,
@@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
49
50
}
50
51
51
52
interface Fetch {
52
- ( context : ComponentInstance ) : void | Promise < void >
53
+ ( context : ComponentInstance ) : any | Promise < any >
54
+ }
55
+ interface UseFetchOptions {
56
+ expose ?: string ,
57
+ manual ?: boolean ,
53
58
}
54
59
55
60
const fetches = new WeakMap < ComponentInstance , Fetch [ ] > ( )
@@ -267,11 +272,27 @@ function getKey(vm: AugmentedComponentInstance) {
267
272
})
268
273
```
269
274
*/
270
- export const useFetch = ( callback : Fetch ) => {
275
+ export const useFetch = ( callback : Fetch , options : UseFetchOptions ) => {
271
276
const vm = getCurrentInstance ( ) as AugmentedComponentInstance | undefined
272
277
if ( ! vm ) throw new Error ( 'This must be called within a setup function.' )
273
278
274
- registerCallback ( vm , callback )
279
+ const resultData = ref ( )
280
+ let callbackProxy : Fetch = async function ( this : any , ...args ) {
281
+ const result = await callback . apply ( this , args )
282
+ resultData . value = result
283
+ return result
284
+ }
285
+ if ( options . manual ) {
286
+ let callbackManually :Fetch = ( ) => {
287
+ callbackManually = callbackProxy
288
+ }
289
+ registerCallback ( vm , callbackManually )
290
+ } else {
291
+ registerCallback ( vm , callbackProxy )
292
+ }
293
+ if ( options . expose ) {
294
+ vm [ options . expose ] = resultData
295
+ }
275
296
276
297
if ( typeof vm . $options . fetchOnServer === 'function' ) {
277
298
vm . _fetchOnServer = vm . $options . fetchOnServer . call ( vm ) !== false
@@ -293,6 +314,7 @@ export const useFetch = (callback: Fetch) => {
293
314
fetchState : vm ! . $fetchState ,
294
315
$fetch : vm ! . $fetch ,
295
316
$fetchState : vm ! . $fetchState ,
317
+ data : resultData ,
296
318
}
297
319
}
298
320
0 commit comments