Skip to content

Commit

Permalink
feat: initialData
Browse files Browse the repository at this point in the history
  • Loading branch information
codercup2 committed May 20, 2024
1 parent 6c38d3a commit 49ef586
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
6 changes: 4 additions & 2 deletions src/hooks/useRequest.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { UnwrapRef } from 'vue'

type IUseRequestOptions<T> = {
/** 是否立即执行,如果是则在onLoad执行 */
immediate?: boolean
Expand All @@ -19,12 +21,12 @@ export default function useRequest<T>(
) {
const loading = ref(false)
const error = ref(false)
const data = ref<T>()
const data = ref<T>(options.initialData)
const run = async () => {
loading.value = true
func()
.then((res) => {
data.value = res.data
data.value = res.data as UnwrapRef<T>
error.value = false
})
.catch((err) => {
Expand Down
18 changes: 13 additions & 5 deletions src/pages/about/components/request.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@

<!-- http://localhost:9000/#/pages/index/request -->
<wd-button @click="run" class="my-6">发送请求</wd-button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-6">{{ JSON.stringify(data) }}</view>
<wd-button type="error" @click="reset" class="my-6">清除数据</wd-button>
<view class="h-12">
<view v-if="loading">loading...</view>
<block v-else>
<view class="text-xl">请求数据如下</view>
<view class="text-green leading-8">{{ JSON.stringify(data) }}</view>
</block>
</view>
<wd-button type="error" @click="reset" class="my-6" :disabled="!data">重置数据</wd-button>
</view>
</template>

Expand All @@ -35,9 +40,12 @@ import { getFooAPI, postFooAPI, IFooItem } from '@/service/index/foo'
const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
const initialData = undefined
// 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'))
const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'), {
initialData,
})
const reset = () => {
data.value = undefined
data.value = initialData
}
</script>

0 comments on commit 49ef586

Please sign in to comment.