当前位置: 首页 > news >正文

nuxt3模块化API架构

nuxt3模块化API架构

composables/useApi.js(核心 composable)↓ 统一底层 api/modules/ ├── projects.js → 基于 useApi()实现 ├── categories.js → 基于 useApi()实现 ├── types.js → 类型定义 └── api.js → 统一导出入口 ↓ Vue 组件调用 pages/*.vue →import{getProjects}from'~/api/projects'

优势

符合 Nuxt3 最佳实践- 使用 composable 模式

模块化组织- 按业务模块分离

向后兼容- Vue 组件调用方式无需修改

代码精简- 删除了冗余的未使用模块

统一底层- 所有 API 调用都基于useApi()

Vue 组件中的调用方式:

import{getProjects}from'~/api/projects'constresponse=awaitgetProjects(params)

附上composables/useApi.js

// composables/useApi.js// 使用 Composable 模式封装 API 请求,符合 Nuxt3 最佳实践import{ofetch}from'ofetch'/** * API Composable Hook * @returns {Object} API 请求方法和工具函数 */exportconstuseApi=()=>{constconfig=useRuntimeConfig()constAPI_BASE_URL=config.public.expressApiUrl||'http://localhost:3001'// 从 localStorage 获取 tokenconstgetToken=()=>{if(import.meta.client){returnlocalStorage.getItem('token')}returnnull}// 创建请求选项constcreateRequestOptions=(customOptions={})=>{consttoken=getToken()constoptions={baseURL:API_BASE_URL,timeout:10000,headers:{'Content-Type':'application/json',...(token&&{Authorization:`Bearer${token}`})},onRequestError:(error)=>{console.error('❌ Request Error:',error)throwerror},onResponseError:({response,error})=>{console.error('❌ Response Error:',error)// 统一错误处理if(response){const{status}=responseconstdata=response._data||{}switch(status){case401:// 未授权,清除 tokenif(import.meta.client){localStorage.removeItem('token')}breakcase403:console.error('没有权限访问')breakcase404:console.error('请求的资源不存在')breakcase500:console.error('服务器内部错误')break}error.message=data?.message||error.message}else{error.message='网络连接失败,请检查网络设置'}throwerror}}return{...options,...customOptions}}// 通用 API 请求函数constrequest=async(config)=>{const{method,url,params,data,...otherOptions}=configconstoptions=createRequestOptions(otherOptions)// 构建完整 URLletfullUrl=urlif(params){constsearchParams=newURLSearchParams(params)constqueryString=searchParams.toString()constseparator=fullUrl.includes('?')?'&':'?'fullUrl=`${url}${separator}${queryString}`}// 添加请求体if(data&&['post','put','patch'].includes(method?.toLowerCase())){options.body=data}// 开发环境日志if(import.meta.client&&window.location.hostname==='localhost'){console.log(`🚀 API Request:${method?.toUpperCase()}${url}`,{params,data,})}try{constresponse=awaitofetch(fullUrl,{...options,method:method?.toLowerCase()})// 开发环境日志if(import.meta.client&&window.location.hostname==='localhost'){console.log(`✅ API Response:${method?.toUpperCase()}${url}`,response)}returnresponse}catch(error){console.error('API 请求错误:',error)throwerror}}// HTTP 方法封装constget=(endpoint,params)=>request({method:'GET',url:endpoint,params})constpost=(endpoint,data)=>request({method:'POST',url:endpoint,data})constput=(endpoint,data)=>request({method:'PUT',url:endpoint,data})constdel=(endpoint)=>request({method:'DELETE',url:endpoint})constpatch=(endpoint,data)=>request({method:'PATCH',url:endpoint,data})// Token 管理consttokenManager={get:getToken,set:(token)=>{if(import.meta.client){localStorage.setItem('token',token)}},remove:()=>{if(import.meta.client){localStorage.removeItem('token')}}}// 导出 ofetch 实例以供特殊情况使用constapiFetch=ofetchreturn{get,post,put,del,patch,tokenManager,request,apiFetch,getBaseUrl:()=>API_BASE_URL}}
http://www.jsqmd.com/news/243807/

相关文章:

  • 系统找不到msvcrt.dll文件 如何修复? 免费下载方法分享
  • 救命神器2026 TOP10 AI论文软件测评:专科生毕业论文救星
  • 学霸同款10个AI论文工具,研究生轻松搞定毕业论文!
  • 系统软件找不到msxml3.dll文件 如何修复? 免费下载方法分享
  • 客户续签率下滑?这套反馈管理,让客户粘性提高80%
  • 系统软件出现找不到msxml3r.dll 如何修复? 免费下载方法分享
  • 如何判断什么时候需要使用RAG
  • 白杨SEO:GEO概念破圈火了,为什么我依旧劝你别轻易丢掉SEO方法?
  • Python | K折交叉验证的参数优化的RANSAC回归预测及可视化算法
  • 腾讯开源WeKnora_IMA框架深度解析
  • 2026年,3D打印行业开年第一展!
  • 怎样用AI技术更快找到合适的客户呢?
  • 什么是漏洞扫描
  • 是时候,让数据开口说话,反哺业务了
  • 简单了解下裸金属服务器
  • 优秀的服务器性能要看哪些方面
  • 题目1103:开心的金明 /题目 1100: 采药
  • Java中接口相关
  • 深度测评9个一键生成论文工具,继续教育学生轻松搞定论文!
  • 人工智能将重塑世界
  • 深度解析21D非线性检测仪:重塑健康预警与亚健康管理的行业白皮书【21D细胞扫描全身健康预警系统应用场景】
  • 靠谱的厌氧池清淤哪个酷
  • 全网最全自考必备AI论文写作软件TOP10测评
  • 学霸同款9个AI论文工具,专科生轻松搞定毕业论文!
  • 口碑好的厌氧池清淤哪个妙
  • 【拯救HMI】帮助系统集成:在HMI界面中提供实时指导
  • 解决CloudCompare不支持PCD格式的问题
  • 【拯救HMI】黑暗模式在工业环境中的应用价值与设计方法
  • 专业安全扫描器竟漏检97%的AI生成后门
  • 可解释AI(XAI)测试:让黑盒模型透明化的工程实践