request2.vue 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <route lang="json5">
  2. {
  3. layout: 'demo',
  4. style: {
  5. navigationBarTitleText: '请求-状态一体化',
  6. },
  7. }
  8. </route>
  9. <template>
  10. <view class="p-6 text-center">
  11. <!-- http://localhost:9000/#/pages/index/request -->
  12. <button @click="getFoo" class="my-6">测试 GET 请求</button>
  13. <view class="text-xl">请求数据如下</view>
  14. <view v-if="loading" class="text-blue h-10">加载中...</view>
  15. <view v-if="error" class="text-red h-10">请求错误</view>
  16. <view v-else class="text-green h-10">{{ JSON.stringify(data) }}</view>
  17. <button class="my-6" type="warn" @click="reset">一键清空数据</button>
  18. </view>
  19. </template>
  20. <script lang="ts" setup>
  21. import { getFooAPI2, IFooItem } from '@/service/index/foo'
  22. import { httpGet } from '@/utils/http'
  23. // 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
  24. const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI2('菲鸽'))
  25. // 再次简化,一行代码搞定,方便一次性的请求,适用大部分请求
  26. // const { loading, error, data, run } = useRequest<IFooItem>(() => httpGet('/foo', { name: '菲鸽' }))
  27. const getFoo = () => run()
  28. const reset = () => {
  29. data.value = undefined
  30. }
  31. </script>