request-openapi.vue 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <script lang="ts" setup>
  2. import type { UserItem } from '@/service'
  3. import { ref } from 'vue'
  4. import useRequest from '@/hooks/useRequest'
  5. import { infoUsingGet } from '@/service/info'
  6. const loading = ref(false)
  7. const error = ref<Error | null>(null)
  8. const data = ref<UserItem>()
  9. async function getUserInfo() {
  10. try {
  11. loading.value = true
  12. // 直接使用openapi生成的请求,需要解构获取promise
  13. const { promise } = await infoUsingGet({})
  14. const res = await promise
  15. console.log(res)
  16. data.value = res
  17. error.value = null
  18. }
  19. catch (err) {
  20. error.value = err as Error
  21. data.value = null
  22. }
  23. finally {
  24. loading.value = false
  25. }
  26. }
  27. // 使用openapi + useRequest生成的请求
  28. const { data: data2, loading: loading2, run } = useRequest<UserItem>(() => infoUsingGet({}), {
  29. immediate: false,
  30. })
  31. </script>
  32. <template>
  33. <view class="p-6 text-center">
  34. <view class="my-4 text-center">
  35. 1)直接使用 openapi 生成的请求
  36. </view>
  37. <view class="my-4 text-center">
  38. <button type="primary" size="mini" class="w-160px" @click="getUserInfo">
  39. 发送请求
  40. </button>
  41. <view class="text-xl">
  42. 请求数据如下
  43. </view>
  44. <view class="text-green leading-8">
  45. {{ JSON.stringify(data) }}
  46. </view>
  47. </view>
  48. <view class="my-4 text-center">
  49. 2)直接使用 openapi + useRequest 生成的请求
  50. </view>
  51. <view class="my-4 text-center">
  52. <button type="primary" size="mini" class="w-160px" @click="run">
  53. 发送请求
  54. </button>
  55. <view class="text-xl">
  56. 请求数据如下
  57. </view>
  58. <view class="text-green leading-8">
  59. {{ JSON.stringify(data2) }}
  60. </view>
  61. </view>
  62. </view>
  63. </template>