在vue开发中,会涉及到很多接口的处理,当项目足够大时,就需要定义规范统一的接口,如何定义呢?
方法可能不只一种,本文使用axios+async/await进行接口的统一管理
本文使用vue-cli生成的项目举例
使用接口管理之前
在项目的某个具体组件中调接口,把调用接口的方法直接写在mounted中,或在是methods中 比如:
xxx.vue
<template> <div id="areaTree"> <!-- 标题 --> <div class="leftTree_Title"> <el-row> <el-col :span="24">{{msg}}</el-col> </el-row> </div> </div></template><script>import axios from 'axios'export default { name: "test", data:function(){ return{ msg:'站点选择', } }, methods:{ }, computed:{ }, //--------------Vue生命周期---具体细节参考:https://puted:{ }, beforeCreate(){ }, created(){ }, beforeMount(){ }, mounted(){ //理解成初始化,该操作只会执行一次 let testdata = GETTREEDATA(); //vue项目接口管理,所有接口都在apis文件夹中统一管理 testdata .then(function(response){ //console.log(response); }).catch(function(error){ console.log(error); }); }, beforeUpdate(){ }, updated(){ }, beforeDestroy(){ }, destroyed(){ },}</script> <style scoped></style>核心部分在 mounted 这块
补充知识:vue项目api接口组织方式
一般后端接口是,一个业务的方法,用一个controller,所以前端这边,一个业务的接口放到一个js文件里
shiroApi提供认证相关接口,如下图
adminApi提供组织,用户,角色管理等相关接口,如下图
将shiroApi和adminApi等等api做个汇总,到apis.js中,如下图
登陆接口调用例子,引入apis.js即可(当然也可以引入具体shiroApi.js,看自己需要和习惯),如下图:
个人总结的api组织方式,欢迎提供更好的建议
以上这篇vue项目接口管理,所有接口都在apis文件夹中统一管理操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。