Sfoglia il codice sorgente

refactor: 请求等页面

菲鸽 1 anno fa
parent
commit
5bdb29994d

+ 25 - 35
src/hooks/useUpload.ts

@@ -1,3 +1,6 @@
+// TODO: 别忘加更改环境变量的 VITE_UPLOAD_BASEURL 地址。
+const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL
+
 /**
  * useUpload 是一个定制化的请求钩子,用于处理上传图片。
  * @param formData 额外传递给后台的数据,如{name: '菲鸽'}。
@@ -7,7 +10,6 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
   const loading = ref(false)
   const error = ref(false)
   const data = ref<T>()
-  const url = import.meta.env.VITE_UPLOAD_BASEURL
   const run = () => {
     // #ifdef MP-WEIXIN
     // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
@@ -19,23 +21,7 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
         console.log(res)
         loading.value = true
         const tempFilePath = res.tempFiles[0].tempFilePath
-        uni.uploadFile({
-          url,
-          filePath: tempFilePath,
-          name: 'file',
-          formData,
-          success: (uploadFileRes) => {
-            console.log(uploadFileRes.data)
-            data.value = uploadFileRes.data as T
-          },
-          fail: (err) => {
-            console.log('uni.uploadFile err->', err)
-            error.value = true
-          },
-          complete: () => {
-            loading.value = false
-          },
-        })
+        uploadFile<T>({ tempFilePath, formData, data, error, loading })
       },
       fail: (err) => {
         console.log('uni.chooseMedia err->', err)
@@ -50,23 +36,7 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
         console.log(res)
         loading.value = true
         const tempFilePath = res.tempFilePaths[0]
-        uni.uploadFile({
-          url,
-          filePath: tempFilePath,
-          name: 'file',
-          formData,
-          success: (uploadFileRes) => {
-            console.log(uploadFileRes.data)
-            data.value = uploadFileRes.data as T
-          },
-          fail: (err) => {
-            console.log('uni.uploadFile err->', err)
-            error.value = true
-          },
-          complete: () => {
-            loading.value = false
-          },
-        })
+        uploadFile<T>({ tempFilePath, formData, data, error, loading })
       },
       fail: (err) => {
         console.log('uni.chooseImage err->', err)
@@ -78,3 +48,23 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
 
   return { loading, error, data, run }
 }
+
+function uploadFile<T>({ tempFilePath, formData, data, error, loading }) {
+  uni.uploadFile({
+    url: VITE_UPLOAD_BASEURL,
+    filePath: tempFilePath,
+    name: 'file',
+    formData,
+    success: (uploadFileRes) => {
+      console.log(uploadFileRes, typeof uploadFileRes.data)
+      data.value = JSON.parse(uploadFileRes.data) as T
+    },
+    fail: (err) => {
+      console.log('uni.uploadFile err->', err)
+      error.value = true
+    },
+    complete: () => {
+      loading.value = false
+    },
+  })
+}

+ 0 - 82
src/hooks/useUpload2.ts

@@ -1,82 +0,0 @@
-/**
- * useUpload 是一个定制化的请求钩子,用于处理上传图片。
- * @param url 上传图片的后台地址,如 https://ukw0y1.laf.run/upload。
- * 如果上传地址是固定的,那就可以配置到 .env 里面,函数里面不需要再传了。
- * @param formData 额外传递给后台的数据,如{name: '菲鸽'}。
- * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
- */
-export default function useUpload<T>(url: string, formData: Record<string, any> = {}) {
-  const loading = ref(false)
-  const error = ref(false)
-  const data = ref<T>()
-
-  const run = () => {
-    // #ifdef MP-WEIXIN
-    // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
-    // 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议
-    uni.chooseMedia({
-      count: 1,
-      mediaType: ['image'],
-      success: (res) => {
-        console.log(res)
-        loading.value = true
-        const tempFilePath = res.tempFiles[0].tempFilePath
-        uni.uploadFile({
-          url,
-          filePath: tempFilePath,
-          name: 'file',
-          formData,
-          success: (uploadFileRes) => {
-            console.log(uploadFileRes.data)
-            data.value = uploadFileRes.data as T
-          },
-          fail: (err) => {
-            console.log('uni.uploadFile err->', err)
-            error.value = true
-          },
-          complete: () => {
-            loading.value = false
-          },
-        })
-      },
-      fail: (err) => {
-        console.log('uni.chooseMedia err->', err)
-        error.value = true
-      },
-    })
-    // #endif
-    // #ifndef MP-WEIXIN
-    uni.chooseImage({
-      count: 1,
-      success: (res) => {
-        console.log(res)
-        loading.value = true
-        const tempFilePath = res.tempFilePaths[0]
-        uni.uploadFile({
-          url,
-          filePath: tempFilePath,
-          name: 'file',
-          formData,
-          success: (uploadFileRes) => {
-            console.log(uploadFileRes.data)
-            data.value = uploadFileRes.data as T
-          },
-          fail: (err) => {
-            console.log('uni.uploadFile err->', err)
-            error.value = true
-          },
-          complete: () => {
-            loading.value = false
-          },
-        })
-      },
-      fail: (err) => {
-        console.log('uni.chooseImage err->', err)
-        error.value = true
-      },
-    })
-    // #endif
-  }
-
-  return { loading, error, data, run }
-}

+ 1 - 1
src/manifest.json

@@ -1,5 +1,5 @@
 {
-  "name": "unibest-base",
+  "name": "unibest",
   "appid": "H57F2ACE4",
   "description": "",
   "versionName": "1.0.0",

+ 0 - 32
src/pages.json

@@ -52,38 +52,6 @@
       "style": {
         "navigationBarTitleText": "关于"
       }
-    },
-    {
-      "path": "pages/index/request",
-      "type": "page",
-      "layout": "demo",
-      "style": {
-        "navigationBarTitleText": "请求"
-      }
-    },
-    {
-      "path": "pages/index/request2",
-      "type": "page",
-      "layout": "demo",
-      "style": {
-        "navigationBarTitleText": "请求-状态一体化"
-      }
-    },
-    {
-      "path": "pages/index/upload",
-      "type": "page",
-      "layout": "default",
-      "style": {
-        "navigationBarTitleText": "上传"
-      }
-    },
-    {
-      "path": "pages/index/upload2",
-      "type": "page",
-      "layout": "default",
-      "style": {
-        "navigationBarTitleText": "上传-状态一体化"
-      }
     }
   ],
   "subPackages": []

+ 5 - 28
src/pages/index/about.vue

@@ -11,44 +11,21 @@
     class="bg-white overflow-hidden pt-2 px-4"
     :style="{ marginTop: safeAreaInsets?.top + 'px' }"
   >
-    <view class="text-center text-3xl mt-4 test-css">关于页面</view>
     <view class="text-center text-3xl mt-8">
       鸽友们好,我是
       <text class="text-red-500">菲鸽</text>
     </view>
-    <view class="text-center mt-8 text-#fff">
-      <wd-button type="primary" @click="gotoPage('request')">去请求页</wd-button>
-      <wd-button type="primary" @click="gotoPage('request2')" custom-class="ml-2">
-        去请求页2 (状态一体)
-      </wd-button>
-    </view>
-
-    <view class="text-center mt-8 text-#fff">
-      <wd-button type="primary" @click="gotoPage('upload')">上传demo</wd-button>
-      <wd-button type="primary" @click="gotoPage('upload2')" custom-class="ml-2">
-        上传demo2(状态一体)
-      </wd-button>
-    </view>
-    <view class="text-center mt-8">
-      <text class="mr-2">iconfont:</text>
-      <view class="inline-flex gap-2 text-red">
-        <view class="iconfont icon-my" />
-        <view class="iconfont icon-chat" />
-        <view class="iconfont icon-package" />
-      </view>
-    </view>
+    <RequestComp />
+    <UploadComp />
   </view>
 </template>
 
 <script lang="ts" setup>
+import RequestComp from './components/request.vue'
+import UploadComp from './components/upload.vue'
+
 // 获取屏幕边界到安全区域距离
 const { safeAreaInsets } = uni.getSystemInfoSync()
-
-const gotoPage = (page: string) => {
-  uni.navigateTo({
-    url: `/pages/index/${page}`,
-  })
-}
 </script>
 
 <style lang="scss" scoped>

+ 43 - 0
src/pages/index/components/request.vue

@@ -0,0 +1,43 @@
+<route lang="json5">
+{
+  layout: 'demo',
+  style: {
+    navigationBarTitleText: '请求',
+  },
+}
+</route>
+
+<template>
+  <view class="p-6 text-center">
+    <view class="my-2">使用的是 laf 云后台</view>
+    <view class="text-green-400">我的推荐码,可以获得佣金</view>
+
+    <!-- #ifdef H5 -->
+    <view class="my-2">
+      <a class="my-2" :href="recommendUrl" target="_blank">{{ recommendUrl }}</a>
+    </view>
+    <!-- #endif -->
+
+    <!-- #ifndef H5 -->
+    <view class="my-2 text-left text-sm">{{ recommendUrl }}</view>
+    <!-- #endif -->
+
+    <!-- http://localhost:9000/#/pages/index/request -->
+    <button @click="run" class="my-6">发送请求</button>
+    <view class="text-xl">请求数据如下</view>
+    <view class="text-green h-6">{{ JSON.stringify(data) }}</view>
+    <button type="warn" @click="reset" class="my-6">清除数据</button>
+  </view>
+</template>
+
+<script lang="ts" setup>
+import { getFooAPI, postFooAPI, IFooItem } from '@/service/index/foo'
+
+const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
+
+// 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
+const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'))
+const reset = () => {
+  data.value = undefined
+}
+</script>

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

@@ -12,18 +12,17 @@
     <wd-button @click="run">选择图片并上传</wd-button>
     <view v-if="loading" class="text-blue h-10">上传...</view>
     <template v-else>
-      <view class="m-2">上传后返回的图片地址:</view>
-      <view class="m-2">{{ data }}</view>
+      <view class="m-2">上传后返回的接口数据:</view>
+      <view class="m-2">{{ JSON.stringify(data) }}</view>
       <view class="h-80 w-full">
-        <image v-if="data" :src="data" mode="scaleToFill" />
+        <image v-if="data" :src="data.url" mode="scaleToFill" />
       </view>
     </template>
   </view>
 </template>
 
 <script lang="ts" setup>
-// const { loading, data, run } = useUpload2<string>('https://ukw0y1.laf.run/upload', { user: '菲鸽' })
-const { loading, data, run } = useUpload<string>({ user: '菲鸽' })
+const { loading, data, run } = useUpload<any>({ user: '菲鸽' })
 </script>
 
 <style lang="scss" scoped>

+ 0 - 67
src/pages/index/request.vue

@@ -1,67 +0,0 @@
-<route lang="json5">
-{
-  layout: 'demo',
-  style: {
-    navigationBarTitleText: '请求',
-  },
-}
-</route>
-
-<template>
-  <view class="p-6 text-center">
-    <view class="my-2">使用的是 laf 云后台</view>
-    <view class="text-green-400">我的推荐码,可以获得佣金</view>
-
-    <!-- #ifdef H5 -->
-    <view class="my-2">
-      <a class="my-2" :href="recommendUrl" target="_blank">{{ recommendUrl }}</a>
-    </view>
-    <!-- #endif -->
-
-    <!-- #ifndef H5 -->
-    <view class="my-2 text-left text-sm">{{ recommendUrl }}</view>
-    <!-- #endif -->
-
-    <!-- http://localhost:9000/#/pages/index/request -->
-    <button @click="getFoo" class="my-6">1.测试 GET 请求</button>
-    <view class="text-xl">请求数据如下</view>
-    <view class="text-green h-10">{{ JSON.stringify(data) }}</view>
-    <view class="text-xl">完整数据</view>
-    <view class="text-green h-16">{{ JSON.stringify(originalData) }}</view>
-    <button @click="postFoo" class="my-6">2.测试 POST 请求</button>
-    <view class="text-xl">请求数据如下</view>
-    <view class="text-green h-10">{{ JSON.stringify(data2) }}</view>
-    <button class="my-6" type="warn" @click="reset">3.一键清空数据</button>
-  </view>
-</template>
-
-<script lang="ts" setup>
-import { getFooAPI, postFooAPI, IFooItem } from '@/service/index/foo'
-
-const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
-
-onLoad(() => {
-  getFoo()
-  postFoo()
-})
-
-const originalData = ref<IResData<IFooItem>>()
-const data = ref<IFooItem>()
-const getFoo = async () => {
-  const res = await getFooAPI('菲鸽')
-  data.value = res.data
-  originalData.value = res
-}
-
-const data2 = ref<IFooItem>()
-const postFoo = async () => {
-  const res = await postFooAPI('菲鸽2')
-  data2.value = res.data
-}
-
-const reset = () => {
-  data.value = undefined
-  data2.value = undefined
-  originalData.value = undefined
-}
-</script>

+ 0 - 35
src/pages/index/request2.vue

@@ -1,35 +0,0 @@
-<route lang="json5">
-{
-  layout: 'demo',
-  style: {
-    navigationBarTitleText: '请求-状态一体化',
-  },
-}
-</route>
-
-<template>
-  <view class="p-6 text-center">
-    <!-- http://localhost:9000/#/pages/index/request -->
-    <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 { getFooAPI2, IFooItem } from '@/service/index/foo'
-import { httpGet } from '@/utils/http'
-
-// 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
-const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI2('菲鸽'))
-// 再次简化,一行代码搞定,方便一次性的请求,适用大部分请求
-// const { loading, error, data, run } = useRequest<IFooItem>(() => httpGet('/foo', { name: '菲鸽' }))
-
-const getFoo = () => run()
-const reset = () => {
-  data.value = undefined
-}
-</script>

+ 0 - 75
src/pages/index/upload.vue

@@ -1,75 +0,0 @@
-<route lang="json5" type="page">
-{
-  layout: 'default',
-  style: {
-    navigationBarTitleText: '上传',
-  },
-}
-</route>
-
-<template>
-  <view class="p-4 text-center">
-    <wd-button @click="chooseImage">选择图片并上传</wd-button>
-    <view class="m-2">上传后返回的图片地址:</view>
-    <view class="m-2">{{ imgStr }}</view>
-    <view class="h-80 w-full">
-      <image v-if="imgStr" :src="imgStr" mode="scaleToFill" />
-    </view>
-  </view>
-</template>
-
-<script lang="ts" setup>
-const imgStr = ref('')
-
-const chooseImage = () => {
-  // #ifdef MP-WEIXIN
-  // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
-  // 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议
-  uni.chooseMedia({
-    count: 1,
-    mediaType: ['image'],
-    success: (res) => {
-      console.log(res)
-      const tempFilePath = res.tempFiles[0].tempFilePath
-      uni.uploadFile({
-        url: 'https://ukw0y1.laf.run/upload',
-        filePath: tempFilePath,
-        name: 'file',
-        formData: {
-          user: '菲鸽',
-        },
-        success: (uploadFileRes) => {
-          console.log(uploadFileRes.data)
-          imgStr.value = uploadFileRes.data
-        },
-      })
-    },
-  })
-  // #endif
-  // #ifndef MP-WEIXIN
-  uni.chooseImage({
-    count: 1,
-    success: (res) => {
-      console.log(res)
-      const tempFilePath = res.tempFilePaths[0]
-      uni.uploadFile({
-        url: 'https://ukw0y1.laf.run/upload',
-        filePath: tempFilePath,
-        name: 'file',
-        formData: {
-          user: '菲鸽',
-        },
-        success: (uploadFileRes) => {
-          console.log(uploadFileRes.data)
-          imgStr.value = uploadFileRes.data
-        },
-      })
-    },
-  })
-  // #endif
-}
-</script>
-
-<style lang="scss" scoped>
-//
-</style>

+ 0 - 18
src/service/index/foo.ts

@@ -6,28 +6,10 @@ export interface IFooItem {
 
 /** GET 请求 */
 export const getFooAPI = (name: string) => {
-  return http<IFooItem>({
-    url: `/foo`,
-    method: 'GET',
-    query: { name },
-  })
-}
-
-/** GET 请求 - 再次简化,看大家是否喜欢这种简化 */
-export const getFooAPI2 = (name: string) => {
   return http.get<IFooItem>('/foo', { name })
 }
 
 /** POST 请求 */
 export const postFooAPI = (name: string) => {
-  return http<IFooItem>({
-    url: `/foo`,
-    method: 'POST',
-    query: { name }, // post 请求也支持 query
-    data: { name },
-  })
-}
-/** POST 请求 - 再次简化,看大家是否喜欢这种简化 */
-export const postFooAPI2 = (name: string) => {
   return http.post<IFooItem>('/foo', { name }, { name })
 }

+ 0 - 2
src/types/auto-import.d.ts

@@ -170,7 +170,6 @@ declare module 'vue' {
     readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
     readonly useRequest: UnwrapRef<typeof import('../hooks/useRequest')['default']>
     readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
-    readonly useUpload2: UnwrapRef<typeof import('../hooks/useUpload2')['default']>
     readonly useUpload: UnwrapRef<typeof import('../hooks/useUpload')['default']>
     readonly watch: UnwrapRef<typeof import('vue')['watch']>
     readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
@@ -254,7 +253,6 @@ declare module '@vue/runtime-core' {
     readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
     readonly useRequest: UnwrapRef<typeof import('../hooks/useRequest')['default']>
     readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
-    readonly useUpload2: UnwrapRef<typeof import('../hooks/useUpload2')['default']>
     readonly useUpload: UnwrapRef<typeof import('../hooks/useUpload')['default']>
     readonly watch: UnwrapRef<typeof import('vue')['watch']>
     readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>

+ 1 - 5
src/types/uni-pages.d.ts

@@ -5,11 +5,7 @@
 
 interface NavigateToOptions {
   url: "/pages/index/index" |
-       "/pages/index/about" |
-       "/pages/index/request" |
-       "/pages/index/request2" |
-       "/pages/index/upload" |
-       "/pages/index/upload2";
+       "/pages/index/about";
 }
 interface RedirectToOptions extends NavigateToOptions {}