编辑 | blame | 历史 | 原始文档

API 调用接口使用指南

快速开始

1. 基础 HTTP 调用

使用 http 工具直接调用接口:

import { http } from '@/utils/http'

// GET 请求
const getUsers = async () => {
  const res = await http.get('/api/user/list', { page: 1, pageSize: 10 })
  return res.data
}

// POST 请求
const createUser = async () => {
  const res = await http.post('/api/user/create', {
    name: '张三',
    age: 25
  })
  return res.data
}

// PUT 请求
const updateUser = async (id) => {
  const res = await http.put(`/api/user/${id}`, {
    name: '李四'
  })
  return res.data
}

// DELETE 请求
const deleteUser = async (id) => {
  const res = await http.delete(`/api/user/${id}`)
  return res.data
}

2. 使用封装的 API 模块

所有接口已统一封装在 /src/api/index.js 中:

import { warehouseApi, inventoryApi, taskApi } from '@/api'

// 获取仓库状态
const warehouse = await warehouseApi.getWarehouseStatus()

// 获取库存列表
const inventory = await inventoryApi.getInventoryList({ page: 1 })

// 获取任务列表
const tasks = await taskApi.getTaskList({ status: '进行中' })

// 创建任务
const newTask = await taskApi.createTask({
  taskNo: 'RK001',
  type: '入库',
  material: '钢板',
  quantity: 100
})

在 Vue 组件中使用

示例1: 简单数据获取

<template>
  <div>
    <el-button @click="fetchData" :loading="loading">获取数据</el-button>
    <div v-if="data">{{ data }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { http } from '@/utils/http'

const loading = ref(false)
const data = ref(null)

const fetchData = async () => {
  loading.value = true
  try {
    const res = await http.get('/api/data')
    data.value = res.data
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

示例2: 使用 API 模块

<template>
  <div>
    <el-table :data="warehouseList" v-loading="loading">
      <el-table-column prop="name" label="仓库名称" />
      <el-table-column prop="capacity" label="容量" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { warehouseApi } from '@/api'

const loading = ref(false)
const warehouseList = ref([])

const fetchWarehouse = async () => {
  loading.value = true
  try {
    const res = await warehouseApi.getAreas()
    warehouseList.value = res.data
  } catch (error) {
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

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

示例3: 表单提交

<template>
  <el-form @submit.prevent="handleSubmit">
    <el-form-item label="任务编号">
      <el-input v-model="form.taskNo" />
    </el-form-item>
    <el-form-item label="任务类型">
      <el-select v-model="form.type">
        <el-option label="入库" value="入库" />
        <el-option label="出库" value="出库" />
      </el-select>
    </el-form-item>
    <el-button type="primary" native-type="submit" :loading="submitting">
      提交
    </el-button>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { taskApi } from '@/api'

const submitting = ref(false)
const form = ref({
  taskNo: '',
  type: '入库'
})

const handleSubmit = async () => {
  submitting.value = true
  try {
    const res = await taskApi.createTask(form.value)
    ElMessage.success('创建成功')
    // 处理返回数据...
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    submitting.value = false
  }
}
</script>

示例4: 并发请求

<script setup>
import { ref, onMounted } from 'vue'
import { warehouseApi, inventoryApi, taskApi } from '@/api'

const dashboardData = ref({
  warehouse: null,
  inventory: null,
  tasks: null
})

const fetchDashboardData = async () => {
  try {
    // 同时发起多个请求,等待全部完成
    const [warehouse, inventory, tasks] = await Promise.all([
      warehouseApi.getWarehouseStatus(),
      inventoryApi.getInventoryOverview(),
      taskApi.getTaskList({ status: '进行中' })
    ])

    dashboardData.value = {
      warehouse: warehouse.data,
      inventory: inventory.data,
      tasks: tasks.data
    }
  } catch (error) {
    console.error('获取看板数据失败:', error)
  }
}

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

API 模块完整列表

warehouseApi - 仓库相关

// 获取仓库状态概览
warehouseApi.getWarehouseStatus()

// 获取仓库区域信息
warehouseApi.getAreas()

// 获取库位信息
warehouseApi.getLocations(params)

// 获取温湿度数据
warehouseApi.getEnvData()

inventoryApi - 库存相关

// 获取库存概览
inventoryApi.getInventoryOverview()

// 获取库存列表
inventoryApi.getInventoryList(params)

// 库存预警列表
inventoryApi.getLowStockAlerts(params)

// 库存积压列表
inventoryApi.getOverStockAlerts(params)

// 即将过期物料
inventoryApi.getExpiringItems(params)

// 库存周转率
inventoryApi.getTurnoverRate(params)

// ABC分类统计
inventoryApi.getABCStats()

taskApi - 任务相关

// 获取任务列表
taskApi.getTaskList(params)

// 创建任务
taskApi.createTask(data)

// 更新任务状态
taskApi.updateTaskStatus(taskId, data)

// 获取任务详情
taskApi.getTaskDetail(taskId)

ioApi - 出入库相关

// 入库单列表
ioApi.getInboundList(params)

// 出库单列表
ioApi.getOutboundList(params)

// 创建入库单
ioApi.createInbound(data)

// 创建出库单
ioApi.createOutbound(data)

// 出入库统计
ioApi.getIOStats(params)

productionApi - 生产相关

// 获取生产线状态
productionApi.getProductionLines()

// 获取设备状态
productionApi.getDeviceStatus(lineId)

// 获取生产任务列表
productionApi.getProductionTasks(params)

// 产量统计
productionApi.getProductionStats(params)

// 良品率统计
productionApi.getQualityStats(params)

// 设备OEE
productionApi.getDeviceOEE(params)

reportApi - 报表相关

// 综合看板数据
reportApi.getDashboardData()

// 出入库趋势
reportApi.getTrendData(params)

// 分类占比
reportApi.getCategoryStats()

// 作业效率统计
reportApi.getEfficiencyStats(params)

错误处理

http 工具已经内置了错误处理:

import { http } from '@/utils/http'

try {
  const res = await http.get('/api/data')
  // res.data 是后端返回的数据
} catch (error) {
  // 错误已经被拦截器处理并显示提示
  // 这里可以做额外的错误处理
  console.error('自定义错误处理:', error)
}

请求/响应拦截器

请求拦截器会自动添加 baseURL 和 headers:

// 在 src/utils/http.js 中配置
const request = axios.create({
  baseURL: '/api',  // 会自动添加到所有请求前
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

响应拦截器会自动处理错误:

// 统一错误提示
ElMessage.error(res.message || '请求失败')

// 统一返回格式
// 假设后端返回: { code: 200, data: {}, message: '' }
// 拦截器会返回 res.data

代理配置

vite.config.js 中配置代理:

server: {
  port: 3000,
  proxy: {
    '/api': {
      target: 'http://localhost:8080',  // 修改为实际后端地址
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, '')
    }
  }
}

访问示例页面

启动项目后,访问 http://localhost:3000/api-example 查看完整的API调用示例和交互演示。