API_USAGE_EXAMPLES.md 6.98 KB

API 使用示例

本文档展示如何使用从 OpenAPI 文档自动生成的 API 接口。

📦 导入 API

// 导入特定模块的 API
import { getUserInfoAPI } from '@/api/user';

🔧 基础用法

示例 1: 简单调用

import { getUserInfoAPI } from '@/api/user';

// 在组件中使用
export default {
  setup() {
    const fetchUserInfo = async () => {
      try {
        const result = await getUserInfoAPI({ id: 123 });

        if (result.code === 1) {
          console.log('用户信息:', result.data);
        } else {
          console.error('获取失败:', result.msg);
        }
      } catch (error) {
        console.error('请求异常:', error);
      }
    };

    return { fetchUserInfo };
  }
}

示例 2: 结合 Pinia Store

// src/stores/user.js
import { defineStore } from 'pinia';
import { getUserInfoAPI } from '@/api/user';

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoading: false,
  }),

  actions: {
    async fetchUserInfo() {
      this.isLoading = true;
      try {
        const result = await getUserInfoAPI();
        if (result.code === 1) {
          this.userInfo = result.data;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
  },
});

示例 3: 在 Vue 3 Composition API 中使用

<template>
  <view>
    <nut-button @click="handleGetUserInfo">获取用户信息</nut-button>
    <view v-if="userInfo">
      <text>{{ userInfo.name }}</text>
      <text>{{ userInfo.mobile }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { getUserInfoAPI } from '@/api/user';

const userInfo = ref(null);

const handleGetUserInfo = async () => {
  try {
    const result = await getUserInfoAPI();
    if (result.code === 1) {
      userInfo.value = result.data.user;
      Taro.showToast({
        title: '获取成功',
        icon: 'success',
      });
    }
  } catch (error) {
    Taro.showToast({
      title: '获取失败',
      icon: 'error',
    });
  }
};
</script>

示例 4: 错误处理和重试

import { getUserInfoAPI } from '@/api/user';

const fetchUserInfoWithRetry = async (retries = 3) => {
  for (let i = 0; i < retries; i++) {
    try {
      const result = await getUserInfoAPI();
      if (result.code === 1) {
        return result.data;
      }
    } catch (error) {
      console.error(`尝试 ${i + 1}/${retries} 失败:`, error);

      if (i === retries - 1) {
        throw error; // 最后一次尝试失败后抛出错误
      }

      // 等待后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
};

示例 5: 结合加载状态

<template>
  <view>
    <nut-button @click="fetchData" :loading="isLoading">
      {{ isLoading ? '加载中...' : '获取用户信息' }}
    </nut-button>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { getUserInfoAPI } from '@/api/user';

const isLoading = ref(false);

const fetchData = async () => {
  isLoading.value = true;
  try {
    const result = await getUserInfoAPI();
    if (result.code === 1) {
      // 处理成功
    }
  } catch (error) {
    // 处理错误
  } finally {
    isLoading.value = false;
  }
};
</script>

🎯 最佳实践

1. 统一错误处理

// src/utils/apiHandler.js
export const handleApiCall = async (apiFunc, params = {}) => {
  try {
    const result = await apiFunc(params);

    if (result.code === 1) {
      return { success: true, data: result.data };
    } else {
      Taro.showToast({
        title: result.msg || '请求失败',
        icon: 'error',
      });
      return { success: false, error: result.msg };
    }
  } catch (error) {
    Taro.showToast({
      title: '网络异常',
      icon: 'error',
    });
    return { success: false, error };
  }
};

// 使用
import { getUserInfoAPI } from '@/api/user';
import { handleApiCall } from '@/utils/apiHandler';

const { success, data, error } = await handleApiCall(getUserInfoAPI);
if (success) {
  console.log(data);
}

2. 请求参数验证

import { getUserInfoAPI } from '@/api/user';

const fetchUserInfo = async (params) => {
  // 参数验证
  if (!params || !params.id) {
    Taro.showToast({
      title: '缺少必要参数',
      icon: 'error',
    });
    return;
  }

  return await getUserInfoAPI(params);
};

3. 缓存机制

import { getUserInfoAPI } from '@/api/user';
import Taro from '@tarojs/taro';

const fetchUserInfoWithCache = async (userId) => {
  const cacheKey = `user_info_${userId}`;
  const cache = Taro.getStorageSync(cacheKey);

  // 如果有缓存且未过期
  if (cache && Date.now() - cache.timestamp < 5 * 60 * 1000) {
    return cache.data;
  }

  // 请求新数据
  const result = await getUserInfoAPI({ id: userId });

  if (result.code === 1) {
    // 缓存数据
    Taro.setStorageSync(cacheKey, {
      data: result.data,
      timestamp: Date.now(),
    });
    return result.data;
  }
};

📚 更多示例

并发请求

import { getUserInfoAPI } from '@/api/user';
import { wxJsAPI } from '@/api/wx/config';

const fetchData = async () => {
  const [userInfo, wxConfig] = await Promise.all([
    getUserInfoAPI(),
    wxJsAPI({ url: window.location.href }),
  ]);

  console.log(userInfo, wxConfig);
};

链式请求

const fetchThenProcess = async () => {
  // 先获取用户信息
  const userResult = await getUserInfoAPI();
  if (userResult.code !== 1) return;

  // 再用用户信息获取其他数据
  const otherResult = await someOtherAPI({
    userId: userResult.data.user.id,
  });
};

🔍 调试技巧

查看请求详情

import { getUserInfoAPI } from '@/api/user';

const debugFetch = async () => {
  console.time('API请求');
  const result = await getUserInfoAPI({ debug: 1 });
  console.timeEnd('API请求');

  console.log('完整响应:', result);
  console.log('状态码:', result.code);
  console.log('返回数据:', result.data);
  console.log('消息:', result.msg);
};

使用 Taro 的网络监控

Taro.request({
  url: '/srv/?a=user_info',
  method: 'GET',
  success: (res) => {
    console.log('请求成功', res);
  },
  fail: (err) => {
    console.error('请求失败', err);
  },
});

💡 提示

  1. 始终检查 code:根据业务逻辑,通常 code === 1 表示成功
  2. 错误处理:使用 try-catch 捕获网络异常
  3. 加载状态:为长时间请求添加加载提示
  4. 参数验证:在调用 API 前验证必要参数
  5. 避免重复请求:可以使用防抖或节流控制请求频率

🚀 下一步