Vue二次封裝axios流程詳解
一、為什么要封裝axios
api統(tǒng)一管理,不管接口有多少,所有的接口都可以非常清晰,容易維護(hù)。
通常我們的項(xiàng)目會(huì)越做越大,頁(yè)面也會(huì)越來(lái)越多,如果頁(yè)面非常的少,直接用axios也沒(méi)有什么大的影響,那頁(yè)面組件多了起來(lái),上百個(gè)接口呢,這個(gè)時(shí)候后端改了接口,多加了一個(gè)參數(shù)什么的呢?那就只有找到那個(gè)頁(yè)面,進(jìn)去修改,整個(gè)過(guò)程很繁瑣,不易于項(xiàng)目的維護(hù)和迭代。
這個(gè)時(shí)候如果我們統(tǒng)一的區(qū)管理接口,需要修改某一個(gè)接口的時(shí)候直接在api里修改對(duì)應(yīng)的請(qǐng)求,是不是很方便呢?因?yàn)槲覀冇玫淖疃嗟倪€是get post請(qǐng)求,我們就可以針對(duì)封裝。
二、怎么封裝axios
1. 拿到項(xiàng)目和后端接口,首先要配置全局代理;
2. 接著全局封裝axios和request.js;
3. 過(guò)濾axios請(qǐng)求方式,控制路徑,參數(shù)的格式,http.js;
4. 正式封裝api.js;
5. 頁(yè)面調(diào)用;
三、具體步驟
vue項(xiàng)目的前期配置
1. 終端輸入
npm i axios -S
2. 在項(xiàng)目中 main.js 文件中輸入
import axios from "axios";
配置config文件中的代理地址
修改項(xiàng)目中config目錄下的index.js文件。【也可能是vue.config.js 文件】
'use strict' // Template version: 1.3.1 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/': '' } }, '/ws/*': { target: 'ws://127.0.0.1:8080', ws: true } }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console. useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
封裝axios實(shí)例-request.js
/**** request.js ****/ // 導(dǎo)入axios import axios from 'axios' // 使用element-ui Message做消息提醒 import { Message} from 'element-ui'; //1. 創(chuàng)建新的axios實(shí)例, const service = axios.create({ // 公共接口--這里注意后面會(huì)講 baseURL: process.env.BASE_API, // 超時(shí)時(shí)間 單位是ms,這里設(shè)置了3s的超時(shí)時(shí)間 timeout: 3 * 1000 }) // 2.請(qǐng)求攔截器 service.interceptors.request.use(config => { //發(fā)請(qǐng)求前做的一些處理,數(shù)據(jù)轉(zhuǎn)化,配置請(qǐng)求頭,設(shè)置token,設(shè)置loading等,根據(jù)需求去添加 config.data = JSON.stringify(config.data); //數(shù)據(jù)轉(zhuǎn)化,也可以使用qs轉(zhuǎn)換 config.headers = { 'Content-Type':'application/json' //配置請(qǐng)求頭 } //如有需要:注意使用token的時(shí)候需要引入cookie方法或者用本地localStorage等方法,推薦js-cookie //const token = getCookie('名稱');//這里取token之前,你肯定需要先拿到token,存一下 //if(token){ //config.params = {'token':token} //如果要求攜帶在參數(shù)中 //config.headers.token= token; //如果要求攜帶在請(qǐng)求頭中 //} return config }, error => { Promise.reject(error) }) // 3.響應(yīng)攔截器 service.interceptors.response.use(response => { //接收到響應(yīng)數(shù)據(jù)并成功后的一些共有的處理,關(guān)閉loading等 return response }, error => { /***** 接收到異常響應(yīng)的處理開(kāi)始 *****/ if (error && error.response) { // 1.公共錯(cuò)誤處理 // 2.根據(jù)響應(yīng)碼具體處理 switch (error.response.status) { case 400: error.message = '錯(cuò)誤請(qǐng)求' break; case 401: error.message = '未授權(quán),請(qǐng)重新登錄' break; case 403: error.message = '拒絕訪問(wèn)' break; case 404: error.message = '請(qǐng)求錯(cuò)誤,未找到該資源' window.location.href = "/NotFound" break; case 405: error.message = '請(qǐng)求方法未允許' break; case 408: error.message = '請(qǐng)求超時(shí)' break; case 500: error.message = '服務(wù)器端出錯(cuò)' break; case 501: error.message = '網(wǎng)絡(luò)未實(shí)現(xiàn)' break; case 502: error.message = '網(wǎng)絡(luò)錯(cuò)誤' break; case 503: error.message = '服務(wù)不可用' break; case 504: error.message = '網(wǎng)絡(luò)超時(shí)' break; case 505: error.message = 'http版本不支持該請(qǐng)求' break; default: error.message = `連接錯(cuò)誤${error.response.status}` } } else { // 超時(shí)處理 if (JSON.stringify(error).includes('timeout')) { Message.error('服務(wù)器響應(yīng)超時(shí),請(qǐng)刷新當(dāng)前頁(yè)') } error.message = '連接服務(wù)器失敗' } Message.error(error.message) /***** 處理結(jié)束 *****/ //如果不需要錯(cuò)誤處理,以上的處理過(guò)程都可省略 return Promise.resolve(error.response) }) //4.導(dǎo)入文件 export default service
四、封裝請(qǐng)求-http.js
/**** http.js ****/ // 導(dǎo)入封裝好的axios實(shí)例 import request from './request' const http ={ /** * methods: 請(qǐng)求 * @param url 請(qǐng)求地址 * @param params 請(qǐng)求參數(shù) */ get(url,params){ const config = { method: 'get', url:url } if(params) config.params = params return request(config) }, post(url,params){ const config = { method: 'post', url:url } if(params) config.data = params return request(config) }, put(url,params){ const config = { method: 'put', url:url } if(params) config.params = params return request(config) }, delete(url,params){ const config = { method: 'delete', url:url } if(params) config.params = params return request(config) } } //導(dǎo)出 export default http
五、正式封裝API用于發(fā)送請(qǐng)求-api.js
import request from "@/utils/request.js"; import qs from "qs"; const baseUrl = '/api/jwt/auth' //登錄 export function authCodeLogin(params) { return request({ url: baseUrl + "/authCodeLogin/" + params.code, method: "get", }); } //退出 export function authLogout(params) { return request({ url: baseUrl + "/logout", method: "get", }); } //獲取用戶數(shù)據(jù) export function getUserInfo(params) { return request({ url: baseUrl + "/getUserInfo", method: "get", params:qs.stringfy(params) }); } //其實(shí),也不一定就是params,也可以是 query 還有 data 的呀! //params是添加到url的請(qǐng)求字符串中的,用于get請(qǐng)求。會(huì)將參數(shù)加到 url后面。所以,傳遞的都是字符串。無(wú)法傳遞參數(shù)中含有json格式的數(shù)據(jù) //而data是添加到請(qǐng)求體(body)中的, 用于post請(qǐng)求。添加到請(qǐng)求體(body)中,json 格式也是可以的。
六、如何在vue文件中調(diào)用
用到哪個(gè)api 就調(diào)用哪個(gè)接口
import { authCodeLogin } from '@/api/api.js' getModellogin(code){ let params = { code: code, } authCodeLogin(params).then(res=>{ if (res.code === 200) { localStorage.clear() // 菜單 this.$store.dispatch('saveMenu', []) // this.getFloorMenu() // this.getmenu() this.$router.push('/') }else{ console.log('error'); } }) },
到此這篇關(guān)于Vue二次封裝axios流程詳解的文章就介紹到這了,更多相關(guān)Vue封裝axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3.0 自己實(shí)現(xiàn)放大鏡效果案例講解
這篇文章主要介紹了Vue3.0 自己實(shí)現(xiàn)放大鏡效果案例講解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07Vue使用Multiavatarjs生成自定義隨機(jī)頭像的案例
這篇文章給大家介紹了Vue項(xiàng)目中使用Multiavatarjs生成自定義隨機(jī)頭像的案例,文中通過(guò)代碼示例介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-10-10vue require.context全局注冊(cè)組件的具體實(shí)現(xiàn)
本文主要介紹了vue require.context全局注冊(cè)組件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05Vue 實(shí)現(xiàn)列表動(dòng)態(tài)添加和刪除的兩種方法小結(jié)
今天小編就為大家分享一篇Vue 實(shí)現(xiàn)列表動(dòng)態(tài)添加和刪除的兩種方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09詳解vue中引入stylus及報(bào)錯(cuò)解決方法
這篇文章主要介紹了詳解vue中引入stylus及報(bào)錯(cuò)解決方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09vue頭部導(dǎo)航動(dòng)態(tài)點(diǎn)擊處理方法
這篇文章主要介紹了vue頭部導(dǎo)航動(dòng)態(tài)點(diǎn)擊處理方法,文中通過(guò)一段示例代碼給大家介紹了vue實(shí)現(xiàn)動(dòng)態(tài)頭部的方法,需要的朋友可以參考下2018-11-11使用Vue3和p5.js實(shí)現(xiàn)交互式圖像動(dòng)畫
這篇文章主要介紹了如何用Vue3和p5.js打造一個(gè)交互式圖像動(dòng)畫,文中給出了詳細(xì)的代碼示例,本代碼適用于需要在網(wǎng)頁(yè)中實(shí)現(xiàn)圖像滑動(dòng)效果的場(chǎng)景,例如圖片瀏覽、相冊(cè)展示等,感興趣的小伙伴跟著小編一起來(lái)看看吧2024-06-06