request.vue 1.9 KB

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