Files
zyt/TUICallKit-Vue3/INTEGRATION_SUMMARY.md
T
2026-03-11 14:33:49 +08:00

6.8 KiB
Raw Blame History

小程序 API 集成总结

核心架构

main.js (全局配置)
  ├── $url: 'http://api.zzzhengyangtang.cn'
  ├── apiUrl: function(promise, loading)
  └── app.config.globalProperties

utils/global.js (全局工具)
  ├── getGlobalProperties()
  ├── getBaseUrl()
  ├── getApiUrl()
  ├── useGlobal()
  └── getFullUrl()

utils/api.js (API 服务)
  ├── request(url, method, data, loading)
  ├── get(url, data, loading)
  ├── post(url, data, loading)
  └── doctorApi { getDoctorList, getDoctorDetail, getDoctorRoster }

pages/index/index.vue (首页)
  └── fetchDoctors() → doctorApi.getDoctorList()

文件说明

1. main.js - 全局配置

定义全局属性:

app.config.globalProperties.$url = baseUrl
app.config.globalProperties.apiUrl = apiUrl

特点:

  • 定义 API 基础 URL
  • 定义 apiUrl 方法(处理 token、加载中、登录失效等)
  • 支持 Vue2 和 Vue3

2. utils/global.js - 全局工具

提供的函数:

  • getGlobalProperties() - 获取全局属性对象
  • getBaseUrl() - 获取 API 基础 URL
  • getApiUrl() - 获取 apiUrl 方法
  • useGlobal() - Composition API Hook
  • getFullUrl(path) - 获取完整 URL
  • setGlobalProperty(key, value) - 设置全局属性
  • getGlobalProperty(key, defaultValue) - 获取特定全局属性

使用示例:

import { useGlobal, getBaseUrl } from '@/utils/global'

const { baseUrl, apiUrl } = useGlobal()
const url = getBaseUrl()

3. utils/api.js - API 服务

提供的方法:

  • request(url, method, data, loading) - 基础请求方法
  • get(url, data, loading) - GET 请求
  • post(url, data, loading) - POST 请求
  • doctorApi - 医生相关 API

医生 API:

doctorApi.getDoctorList(params)      // 获取医生列表
doctorApi.getDoctorDetail(id)        // 获取医生详情
doctorApi.getDoctorRoster(id, date)  // 获取医生排班

特点:

  • 自动使用全局 $urlapiUrl
  • 降级方案:当全局方法不可用时,直接使用 uni.request
  • 自动处理 token 和请求头

4. pages/index/index.vue - 首页

功能:

  • 展示古典卷轴风格幻灯片
  • 动态加载医生列表
  • 医生卡片点击跳转

流程:

onMounted()
  ↓
fetchDoctors()
  ↓
doctorApi.getDoctorList()
  ↓
request() → apiUrl() → uni.request()
  ↓
更新 doctors 数据
  ↓
医生卡片渲染

使用流程

1. 在组件中使用 API

<script setup>
import { ref, onMounted } from 'vue'
import { doctorApi } from '../utils/api'

const doctors = ref([])

const fetchDoctors = async () => {
  try {
    const response = await doctorApi.getDoctorList({
      page_no: 1,
      page_size: 10
    })
    
    if (response.code === 1) {
      doctors.value = response.data.lists || []
    } else {
      uni.showToast({
        title: response.msg || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('请求失败:', error)
  }
}

onMounted(() => {
  fetchDoctors()
})
</script>

2. 使用全局工具

<script setup>
import { useGlobal } from '@/utils/global'

const { baseUrl, apiUrl } = useGlobal()

console.log('Base URL:', baseUrl)
</script>

3. 添加新的 API

utils/api.js 中添加:

export const appointmentApi = {
  getList: (params) => get('/api/appointment/lists', params, false),
  create: (data) => post('/api/appointment/create', data, true),
  cancel: (id) => post('/api/appointment/cancel', { id }, true)
}

请求流程详解

正常流程

组件调用 doctorApi.getDoctorList()
  ↓
调用 get('/api/doctor/lists', params, false)
  ↓
调用 request('/api/doctor/lists', 'GET', params, false)
  ↓
获取全局属性 ($url, apiUrl)
  ↓
调用 apiUrl({ url, method, data, header }, loading)
  ↓
main.js 中的 apiUrl 方法处理
  ↓
获取 token,合并请求头
  ↓
调用 uni.request()
  ↓
返回响应数据
  ↓
检查 code 字段
  ├─ code === 1: 成功,返回数据
  ├─ code === -1: 登录失效,清除 token
  └─ code === 0: 失败,返回错误信息

降级流程

当全局 apiUrl 不可用时:

request() 检查 apiUrl 是否存在
  ↓
apiUrl 不存在
  ↓
使用降级方案:直接调用 uni.request()
  ↓
获取 token,构建完整 URL
  ↓
调用 uni.request()
  ↓
返回响应数据

配置修改

修改 API 基础 URL

编辑 main.js

var baseUrl = 'http://your-api-domain/api'

修改超时时间

编辑 main.js 中的 uni.request

timeout: 20000  // 改为 20 秒

修改请求头

编辑 main.js 中的 header 对象:

const header = {
  token: token,
  'content-type': 'application/x-www-form-urlencoded',
  'X-Custom-Header': 'custom-value'
}

错误处理

自动处理

  1. 登录失效 (code === -1)

    • 自动清除 token
    • 可选:跳转到登录页
  2. 网络错误

    • 自动显示/隐藏加载中
    • 返回错误信息

手动处理

try {
  const response = await doctorApi.getDoctorList({ page_no: 1 })
  
  if (response.code === 1) {
    // 成功
    console.log(response.data)
  } else if (response.code === -1) {
    // 登录失效
    uni.redirectTo({ url: '/pages/login/login' })
  } else {
    // 其他错误
    uni.showToast({
      title: response.msg || '请求失败',
      icon: 'none'
    })
  }
} catch (error) {
  // 网络错误
  console.error('网络错误:', error)
}

最佳实践

  1. 统一 API 管理:所有 API 调用都通过 utils/api.js
  2. 错误处理:始终使用 try-catch 处理异步请求
  3. 加载状态:在请求时显示加载中,完成后隐藏
  4. 响应验证:检查 code 字段判断请求是否成功
  5. token 管理:自动处理 token 过期情况
  6. 全局属性:使用 utils/global.js 中的工具函数访问全局属性

相关文件

  • 全局配置: TUICallKit-Vue3/main.js
  • 全局工具: TUICallKit-Vue3/utils/global.js
  • API 服务: TUICallKit-Vue3/utils/api.js
  • 首页组件: TUICallKit-Vue3/pages/index/index.vue
  • 全局属性说明: TUICallKit-Vue3/GLOBAL_PROPERTIES_USAGE.md
  • API 使用指南: TUICallKit-Vue3/API_USAGE_GUIDE.md
  • API 配置说明: TUICallKit-Vue3/API_CONFIG.md

总结

已完成小程序与后端 API 的完整集成:

  1. 全局配置管理(main.js
  2. 全局工具函数(utils/global.js
  3. API 服务层封装(utils/api.js
  4. 首页医生列表展示(pages/index/index.vue
  5. 完整的错误处理和加载状态
  6. 详细的文档和使用指南

小程序现在可以正常调用后端 API 获取医生列表,并且所有 API 请求都使用 main.js 中定义的全局 $urlapiUrl 方法。