瀏覽代碼

refine: 再次简化请求

菲鸽 2 年之前
父節點
當前提交
86846486ac
共有 3 個文件被更改,包括 16 次插入15 次删除
  1. 4 5
      src/pages/index/request2.vue
  2. 0 4
      src/service/index/foo.d.ts
  3. 12 6
      src/service/index/foo.ts

+ 4 - 5
src/pages/index/request2.vue

@@ -13,21 +13,20 @@
     <button @click="getFoo" class="my-6">测试 GET 请求</button>
     <view class="text-xl">请求数据如下</view>
     <view v-if="loading" class="text-blue h-10">加载中...</view>
+    <view v-if="error" class="text-red h-10">请求错误</view>
     <view v-else class="text-green h-10">{{ JSON.stringify(data) }}</view>
     <button class="my-6" type="warn" @click="reset">一键清空数据</button>
   </view>
 </template>
 
 <script lang="ts" setup>
-import { getFooAPI, IFooItem } from '@/service/index/foo'
+import { getFooAPI2, IFooItem } from '@/service/index/foo'
 import { httpGet } from '@/utils/http'
 
 // 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
-// const { loading, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'), { immediate: true })
+const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI2('菲鸽'))
 // 再次简化,一行代码搞定,方便一次性的请求,适用大部分请求
-const { loading, data, run } = useRequest<IFooItem>(() => httpGet('/foo', { name: '菲鸽' }), {
-  immediate: true,
-})
+// const { loading, error, data, run } = useRequest<IFooItem>(() => httpGet('/foo', { name: '菲鸽' }))
 
 const getFoo = () => run()
 const reset = () => {

+ 0 - 4
src/service/index/foo.d.ts

@@ -1,4 +0,0 @@
-export interface IFooItem {
-  id: string
-  name: string
-}

+ 12 - 6
src/service/index/foo.ts

@@ -1,9 +1,10 @@
-import { http } from '@/utils/http'
-import type { IFooItem } from './foo.d'
-
-export { IFooItem }
+import { http, httpGet } from '@/utils/http'
+export interface IFooItem {
+  id: string
+  name: string
+}
 
-/** get 请求 */
+/** GET 请求 */
 export const getFooAPI = (name: string) => {
   return http<IFooItem>({
     url: `/foo`,
@@ -12,7 +13,12 @@ export const getFooAPI = (name: string) => {
   })
 }
 
-/** get 请求 */
+/** GET 请求 - 再次简化,看大家是否喜欢这种简化 */
+export const getFooAPI2 = (name: string) => {
+  return httpGet<IFooItem>('/foo', { name })
+}
+
+/** POST 请求 */
 export const postFooAPI = (name: string) => {
   return http<IFooItem>({
     url: `/foo`,