更新:登录功能
This commit is contained in:
35
hooks/useRequest.ts
Normal file
35
hooks/useRequest.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
// hooks/useRequest.ts
|
||||
import { ref } from 'vue'
|
||||
|
||||
interface IUseRequestOptions<T> {
|
||||
immediate?: boolean
|
||||
initialData?: T
|
||||
}
|
||||
|
||||
export function useRequest<T>(
|
||||
func: () => Promise<T>,
|
||||
options: IUseRequestOptions<T> = { immediate: false },
|
||||
) {
|
||||
const loading = ref(false)
|
||||
const error = ref<any>(null)
|
||||
const data = ref<T | undefined>(options.initialData)
|
||||
|
||||
const run = async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const res = await func()
|
||||
data.value = res
|
||||
return res
|
||||
} catch (err) {
|
||||
error.value = err
|
||||
throw err
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
options.immediate && run()
|
||||
|
||||
return { loading, error, data, run }
|
||||
}
|
||||
Reference in New Issue
Block a user