request.vue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <script lang="ts" setup>
  2. import type { IFooItem } from '@/api/foo'
  3. import { getFooAPI } from '@/api/foo'
  4. // const initialData = {
  5. // name: 'initialData',
  6. // id: '1234',
  7. // }
  8. const initialData = undefined
  9. // 直接请求示例
  10. async function reqFooAPI() {
  11. try {
  12. const res = await getFooAPI('菲鸽')
  13. console.log('直接请求示例res', res)
  14. }
  15. catch (err) {
  16. console.log(err)
  17. }
  18. }
  19. reqFooAPI()
  20. // 直接useRequest请求示例
  21. const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'), {
  22. immediate: true,
  23. initialData,
  24. })
  25. function reset() {
  26. data.value = initialData
  27. }
  28. </script>
  29. <template>
  30. <view class="p-6 text-center">
  31. <view class="my-2">
  32. pages 里面的 vue 文件会扫描成页面,将自动添加到 pages.json 里面。
  33. </view>
  34. <view class="my-2 text-green-400">
  35. 但是 components 里面的 vue 不会。
  36. </view>
  37. <view class="my-4 text-center">
  38. <button type="primary" size="mini" class="w-160px" @click="run">
  39. 发送请求
  40. </button>
  41. </view>
  42. <view class="h-16">
  43. <view v-if="loading">
  44. loading...
  45. </view>
  46. <block v-else>
  47. <view v-if="error instanceof Error" class="text-red leading-8">
  48. 错误: {{ error.message }}
  49. </view>
  50. <view v-else-if="error" class="text-red leading-8">
  51. 错误: 未知错误
  52. </view>
  53. <view v-else>
  54. <view class="text-xl">
  55. 请求数据如下
  56. </view>
  57. <view class="text-green leading-8">
  58. {{ JSON.stringify(data) }}
  59. </view>
  60. </view>
  61. </block>
  62. </view>
  63. <view class="my-4 text-center">
  64. <button type="warn" size="mini" class="w-160px" :disabled="!data" @click="reset">
  65. 重置数据
  66. </button>
  67. </view>
  68. </view>
  69. </template>