11import {
2+ ref ,
23 isRef ,
34 onBeforeMount ,
45 onServerPrefetch ,
@@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
4950}
5051
5152interface Fetch {
52- ( context : ComponentInstance ) : void | Promise < void >
53+ ( context : ComponentInstance ) : any | Promise < any >
54+ }
55+ interface UseFetchOptions {
56+ expose ?: string ,
57+ manual ?: boolean ,
5358}
5459
5560const fetches = new WeakMap < ComponentInstance , Fetch [ ] > ( )
@@ -267,11 +272,27 @@ function getKey(vm: AugmentedComponentInstance) {
267272 })
268273 ```
269274 */
270- export const useFetch = ( callback : Fetch ) => {
275+ export const useFetch = ( callback : Fetch , options : UseFetchOptions ) => {
271276 const vm = getCurrentInstance ( ) as AugmentedComponentInstance | undefined
272277 if ( ! vm ) throw new Error ( 'This must be called within a setup function.' )
273278
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+ }
275296
276297 if ( typeof vm . $options . fetchOnServer === 'function' ) {
277298 vm . _fetchOnServer = vm . $options . fetchOnServer . call ( vm ) !== false
@@ -293,6 +314,7 @@ export const useFetch = (callback: Fetch) => {
293314 fetchState : vm ! . $fetchState ,
294315 $fetch : vm ! . $fetch ,
295316 $fetchState : vm ! . $fetchState ,
317+ data : resultData ,
296318 }
297319 }
298320
0 commit comments