Vue接口封裝的完整步驟記錄
首先根據(jù)接口寫好對應(yīng)頁面的請求
內(nèi)容如圖盡量保證js文件名稱與頁面文件名稱相同(易于查找)
根據(jù)文件目錄動態(tài)引入/導(dǎo)出接口
提高便捷性
/** * 自動引入當(dāng)前文件夾下所有module * require.context(directory, useSubdirectories = false, regExp = /^.//); * @param {String} directory 讀取文件的路徑 * @param {Boolean} directory 匹配文件的正則表達式 * @param {regExp} regExp 讀取文件的路徑 */ const modulesFiles = require.context( './', // 在當(dāng)前目錄下查找 false, // 不遍歷子文件夾 /\.js$/ // 正則匹配 以 .js結(jié)尾的文件 ) const modules = modulesFiles.keys().reduce((modules, modulePath) => { const moduleName = modulePath.replace(/^.\/(.*)\.js/,'$1') const value = modulesFiles(modulePath) modules[moduleName] = value.default return modules }, {}) export default modules
根據(jù)項目情況編寫攔截/插入內(nèi)容
import axios from 'axios' import { MessageBox, Message } from 'element-ui' import store from '@/store' import { getToken } from '@/utils/auth' // create an axios instance const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // request timeout }) // request interceptor service.interceptors.request.use( config => { // 在發(fā)送請求之前做些什么 if (store.getters.token) { // let each request carry token讓每個請求攜帶令牌 // ['X-Token'] is a custom headers key 是一個自定義標(biāo)題鍵 // please modify it according to the actual situation請根據(jù)實際情況修改 config.headers['X-Token'] = getToken() } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } ) // response interceptor service.interceptors.response.use( /** * If you want to get http information such as headers or status如果您想獲取http信息,如標(biāo)頭或狀態(tài) * Please return response => response */ /** * Determine the request status by custom code通過自定義代碼確定請求狀態(tài) * Here is just an example這里只是一個例子 * You can also judge the status by HTTP Status Code您還可以通過HTTP狀態(tài)碼來判斷狀態(tài) */ response => { const res = response.data // console.log(res); // 如果自定義代碼不是20000,則判斷為錯誤. if (res.code !== 200) { Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 }) // 50008: 非法token; 50012: 其他客戶端已登錄; 50014: Token 已過期; if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // to re-login MessageBox.confirm('您已注銷,可以取消以停留在此頁面,或重新登錄', '確認(rèn)注銷', { confirmButtonText: 'Re-Login', cancelButtonText: 'Cancel', type: 'warning' }).then(() => { store.dispatch('user/resetToken').then(() => { location.reload() }) }) } return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { console.log('err' + error) // for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) export default service
編寫env文件
# just a flag ENV = 'development' # base api VUE_APP_BASE_API = 'http://192.168.2.44:5001/v1'
vue繼承api
import serve from './api/index' Vue.prototype.$api = serve;
使用
getAssetsList() { this.$api.assets .getAssetsList(this.queryInfo.num, this.queryInfo.size) .then((res) => { this.assetsList = res.data.cards this.total = res.data.page.totalCount }) .catch(() => { this.$message.error({ message: "失敗", duration: 700, }) }) },
總結(jié)
到此這篇關(guān)于Vue接口封裝的文章就介紹到這了,更多相關(guān)Vue接口封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue mvvm數(shù)據(jù)響應(yīng)實現(xiàn)
這篇文章主要介紹了vue mvvm數(shù)據(jù)響應(yīng)實現(xiàn)的方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下2020-11-11vue3+elementplus前端生成圖片驗證碼完整代碼舉例
在開發(fā)過程中有時候需要使用圖片驗證碼進行增加安全強度,在點擊圖片時更新新的圖片驗證碼,記錄此功能,以便后期使用,這篇文章主要給大家介紹了關(guān)于vue3+elementplus前端生成圖片驗證碼的相關(guān)資料,需要的朋友可以參考下2024-03-03elementUI樣式修改未生效問題詳解(掛載到了body標(biāo)簽上)
vue+elementUI項目開發(fā)中,經(jīng)常遇到修改elementUI組件樣式無效的問題,這篇文章主要給大家介紹了關(guān)于elementUI樣式修改未生效問題的相關(guān)資料,掛載到了body標(biāo)簽上,需要的朋友可以參考下2023-04-04淺談Vue-cli單文件組件引入less,sass,css樣式的不同方法
下面小編就為大家分享一篇淺談Vue-cli單文件組件引入less,sass,css樣式的不同方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03el-table實現(xiàn)給每行添加loading效果案例
這篇文章主要介紹了el-table實現(xiàn)給每行添加loading效果案例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08element-plus/element-ui走馬燈配置圖片及圖片自適應(yīng)的最簡便方法
走馬燈功能在展示圖片時經(jīng)常用到,下面這篇文章主要給大家介紹了關(guān)于element-plus/element-ui走馬燈配置圖片及圖片自適應(yīng)的最簡便方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03vue如何根據(jù)不同的環(huán)境使用不同的接口地址
這篇文章主要介紹了vue如何根據(jù)不同的環(huán)境使用不同的接口地址問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04