feat(请求): 添加alova请求演示页面及功能

新增alova请求演示页面,包含请求发送和重置功能
修改alova配置,添加请求拦截器和错误处理
This commit is contained in:
feige996
2025-06-22 16:47:41 +08:00
parent dfc9d0f158
commit dcb100e87d
4 changed files with 107 additions and 2 deletions

View File

@@ -59,6 +59,14 @@
"style": {
"navigationBarTitleText": "关于"
}
},
{
"path": "pages/about/alova",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "Alova 请求演示"
}
}
],
"subPackages": []

View File

@@ -20,6 +20,12 @@ const { safeAreaInsets } = uni.getSystemInfoSync()
// }
// testOxlint('oxlint')
console.log('about')
function gotoAlova() {
uni.navigateTo({
url: '/pages/about/alova',
})
}
</script>
<template>
@@ -32,6 +38,9 @@ console.log('about')
</view>
<RequestComp />
<UploadComp />
<button @click="gotoAlova">
前往 alova 页面
</button>
</view>
</template>

60
src/pages/about/alova.vue Normal file
View File

@@ -0,0 +1,60 @@
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: 'Alova 请求演示',
},
}
</route>
<script lang="ts" setup>
import { useRequest } from 'alova/client'
import { http } from '@/utils/request/alova'
const initialData = undefined
function list() {
return http.Get('/foo', {
params: {
name: '菲鸽',
page: 1,
pageSize: 10,
},
})
}
const { loading, data, send } = useRequest(list, {
initialData,
immediate: true,
})
console.log(data)
function reset() {
data.value = initialData
}
</script>
<template>
<view class="p-6 text-center">
<wd-button class="my-6" @click="send">
发送请求
</wd-button>
<view class="h-16">
<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" class="my-6" :disabled="!data" @click="reset">
重置数据
</wd-button>
</view>
</template>
<style lang="scss" scoped>
//
</style>

View File

@@ -1,7 +1,35 @@
import AdapterUniapp from '@alova/adapter-uniapp'
import { createAlova } from 'alova'
const http = createAlova({
baseURL: import.meta.env.VITE_APP_PROXY_PREFIX,
const baseURL = JSON.parse(__VITE_APP_PROXY__)
? import.meta.env.VITE_APP_PROXY_PREFIX
: import.meta.env.VITE_SERVER_BASEURL
export const http = createAlova({
baseURL,
...AdapterUniapp(),
async responded(res: UniApp.RequestSuccessCallbackResult, method) {
console.log('responded:', method, res)
// 请求成功的拦截器
// 状态码 2xx参考 axios 的设计
const resData = res.data as IResData<any>
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
return resData.data
}
else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
// userStore.clearUserInfo()
// uni.navigateTo({ url: '/pages/login/login' })
console.log(res)
throw new Error(resData.msg || '401错误')
}
else {
uni.showToast({
icon: 'none',
title: (resData).msg || '请求错误',
})
throw new Error(resData.msg || '请求错误')
}
},
})