refactor: 请求等页面

This commit is contained in:
菲鸽 2024-05-15 10:06:51 +08:00
parent 2b41626a96
commit 5bdb29994d
13 changed files with 79 additions and 385 deletions

View File

@ -1,3 +1,6 @@
// TODO: 别忘加更改环境变量的 VITE_UPLOAD_BASEURL 地址。
const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL
/** /**
* useUpload * useUpload
* @param formData {name: '菲鸽'} * @param formData {name: '菲鸽'}
@ -7,7 +10,6 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
const loading = ref(false) const loading = ref(false)
const error = ref(false) const error = ref(false)
const data = ref<T>() const data = ref<T>()
const url = import.meta.env.VITE_UPLOAD_BASEURL
const run = () => { const run = () => {
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
// 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。 // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
@ -19,23 +21,7 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
console.log(res) console.log(res)
loading.value = true loading.value = true
const tempFilePath = res.tempFiles[0].tempFilePath const tempFilePath = res.tempFiles[0].tempFilePath
uni.uploadFile({ uploadFile<T>({ tempFilePath, formData, data, error, loading })
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) => { fail: (err) => {
console.log('uni.chooseMedia err->', err) console.log('uni.chooseMedia err->', err)
@ -50,23 +36,7 @@ export default function useUpload<T>(formData: Record<string, any> = {}) {
console.log(res) console.log(res)
loading.value = true loading.value = true
const tempFilePath = res.tempFilePaths[0] const tempFilePath = res.tempFilePaths[0]
uni.uploadFile({ uploadFile<T>({ tempFilePath, formData, data, error, loading })
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) => { fail: (err) => {
console.log('uni.chooseImage err->', 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 } 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
},
})
}

View File

@ -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 }
}

View File

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

View File

@ -52,38 +52,6 @@
"style": { "style": {
"navigationBarTitleText": "关于" "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": [] "subPackages": []

View File

@ -11,44 +11,21 @@
class="bg-white overflow-hidden pt-2 px-4" class="bg-white overflow-hidden pt-2 px-4"
:style="{ marginTop: safeAreaInsets?.top + 'px' }" :style="{ marginTop: safeAreaInsets?.top + 'px' }"
> >
<view class="text-center text-3xl mt-4 test-css">关于页面</view>
<view class="text-center text-3xl mt-8"> <view class="text-center text-3xl mt-8">
鸽友们好我是 鸽友们好我是
<text class="text-red-500">菲鸽</text> <text class="text-red-500">菲鸽</text>
</view> </view>
<view class="text-center mt-8 text-#fff"> <RequestComp />
<wd-button type="primary" @click="gotoPage('request')">去请求页</wd-button> <UploadComp />
<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>
</view> </view>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import RequestComp from './components/request.vue'
import UploadComp from './components/upload.vue'
// //
const { safeAreaInsets } = uni.getSystemInfoSync() const { safeAreaInsets } = uni.getSystemInfoSync()
const gotoPage = (page: string) => {
uni.navigateTo({
url: `/pages/index/${page}`,
})
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -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>

View File

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

View File

@ -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>

View File

@ -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>

View File

@ -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
// 20231017使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>

View File

@ -6,28 +6,10 @@ export interface IFooItem {
/** GET 请求 */ /** GET 请求 */
export const getFooAPI = (name: string) => { 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 }) return http.get<IFooItem>('/foo', { name })
} }
/** POST 请求 */ /** POST 请求 */
export const postFooAPI = (name: string) => { 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 }) return http.post<IFooItem>('/foo', { name }, { name })
} }

View File

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

View File

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