今天我打算跟大家聊一下API封裝,像我們使用VUE來進行流媒體伺服器的展示架構的時候,幾乎都會把API封裝一下,不要小瞧了這個封裝的步驟,有可能在後期為我們帶來很大的便利,封裝一方面是為了使代碼更加規範,另一方面也是便于後期調整。本文就來講一下vue封裝api接口的流程。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2Pn5GcugGO5kXe1FzNtR2LchDN2AjMyczLcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
1,本文使用axios請求,先在require中配置伺服器請求攔截,并添加token,本文模拟token添加1111,域名使用的本地域名,需要自己配置一下,token可以使用cookie。
import axios from 'axios'
// 建立axios對象
let service = axios.create({
baseURL: 'http://127.0.0.1:3001', // 請求接口的域名
timeout: 9000 // 請求的逾時
})
// 添加請求攔截器,
service.interceptors.request.use(
request => {
// 設定請求的頭資訊
request.headers = {
token: `1111`, // 請求添加的token
'Content-Type': 'application/json;charset=utf-8'
}
return request
},
error => {
Promise.reject(error)
}
)
// 添加響應攔截器
service.interceptors.response.use(
response => {
return response.data
},
error => {
Promise.reject(error)
}
)
export default service
複制
2,建立一個接口檔案,統一把接口放入這個js中,使用時直接拿取,合理運用封裝子產品
// 所有接口位址
export default {
exhibitionHotUrl: '/api/exhibition/list',
}
複制
3,封裝api,使用直接拿取api請求
import requset from '../utils/request'
import apiUrl from '../utils/apiUrl'
// 擷取資料
export const getExhibitionList = params => {
return requset({
url: apiUrl.exhibitionHotUrl,
method: 'get',
params
})
}
}
複制
4,最後頁面可以使用
//擷取
import {getExhibitionList} from '../../api/index'
getExhibitionHotList = async () => {
// await 調用
const result = await getExhibitionList({
可以在這裡寫需要傳遞的參數
})
if (result.code === 200) {
this.setState({
//成功資料指派
exhibitionList: result.data.list
})
}
}
複制
這樣封裝api接口差不多就完成了。