在vue開發中,會涉及到很多接口的處理,當項目足夠大時,就需要定義規范統一的接口,如何定義呢?
本文使用vue-cli生成的項目舉例。
第一步.在src目錄下新建一個文件夾http,在http目錄下建文件夾moudules,后台提供的所有接口都在這里定義.
第二步.在moudules目錄下划分模塊新建js文件,比如:
a.會員中心模塊: member.js
b.登錄注冊模塊: login.js
c.合伙人模塊: partner.js
目錄大概是這個樣子:
第三步,需要引入axios做相應的配置。
1.首先安裝axios
npm install axios
2.在http目錄下新建axios.js:
/* jshint esversion: 6 */ import axios from 'axios'; import Cookies from "js-cookie"; import config from './config'; import router from '@/router'; import { Toast} from 'vant'; export default function $axios(options) { return new Promise((resolve, reject) => { const instance = axios.create({ baseURL: config.baseUrl, headers: config.headers, timeout: config.timeout, withCredentials: config.withCredentials, }); // request 攔截器
instance.interceptors.request.use( config => { //在發送之前做點什么
let auth_token = Cookies.get('auth_token'); if (auth_token) { config.headers.auth_token = auth_token; } else { let loginpage = Cookies.get('loginpage'); if (loginpage) { router.push('/login'); } } if (config.method === 'post') {} return config; }, error => { // 判斷請求超時
if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) { Toast("信號不好,請求超時") } } ); // response 攔截器
instance.interceptors.response.use( response => { //對響應數據做點什么
let data; if (response.data == undefined) { data = JSON.parse(response.request.responseText); } else { data = response.data; } return data; }, err => { if (err && err.response) { console.log(err) }// 返回接口返回的錯誤信息
return Promise.reject(err); } ); // 請求處理
instance(options).then(res => { resolve(res); return false; }).catch(error => { reject(error); }); }); }
3.在http目錄下新建config.js:
export default { method: 'get', // 基礎url前綴
baseUrl: baseUrl,//請求的域名地址
// 請求頭信息
headers: { 'Content-Type': 'application/json;charset=UTF-8' }, // 參數
data: {}, // 設置超時時間
timeout: 10000, // 攜帶憑證
withCredentials: false, // 返回數據類型
responseType: 'json' }
第四步,在http下面的js文件中引入api.js
導出的函數,拿其中一個文件login.js
說明:
1.api.js:
/* jshint esversion: 6 */ import * as login from './moudules/login'; // 默認導出
export default { login, }
2.login.js
import axios from '../axios'
/* * 系統登錄模塊 */
// 登錄
export const login = (data) => { return axios({ url: '/app/api/v1/user/phonelogin', method: 'post', data }); };
第五步:將api掛載在 Vue 原型的 $api 對象上
1.在http文件下新建index.js文件:
import api from './api'; const install = Vue => { if (install.installed) return; install.installed = true; Object.defineProperties(Vue.prototype, { // 注意,此處掛載在 Vue 原型的 $api 對象上
$api: { get() { return api } } }); }; export default install
2.在項目的main.js文件下導入api:
import api from './http'; Vue.use(api);
第六步步,在組件中使用接口,比如在登陸頁面中使用login的接口:
let loginInfo = { phone: this.field.phone, code: this.field.sms, cityname: this.field.city }; this.$api.login.login(loginInfo).then(res => { if (res.ret == 0) { Cookies.set("auth_token", res.data.authToken); this.$toast.success({message:"登錄成功",duration:2000}); setTimeout(() => { this.loading = false; this.$router.go(-1); }, 2000); } })
最終http目錄為:
以上方法定義接口雖然看起來麻煩點,但有卻有其好處:
-
代碼看起來規范,所有的接口都在一個文件夾定義,不用分散的各個組件,方便維護管理。
-
可以做到接口一次定義,多處使用。