日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > vue >内容正文

vue

vue项目请求封装;axios封装使用

發(fā)布時(shí)間:2023/12/9 vue 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue项目请求封装;axios封装使用 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

vue項(xiàng)目,封裝axios請(qǐng)求方式和響應(yīng)狀態(tài)碼;以及接口的api封裝;

目錄結(jié)構(gòu):

1.具體在src/utils/request.js下封裝axios:
①引入axios和router
②引入element-ui是為了用提示組件 和加載組件(可選擇去掉)
③根據(jù)請(qǐng)求攔截器的config配置請(qǐng)求頭
④根據(jù)響應(yīng)攔截器的不同狀態(tài)碼做不同處理(狀態(tài)碼需要自己根據(jù)項(xiàng)目修改)
簡(jiǎn)單的request.js封裝點(diǎn)擊這里,沒(méi)有封裝狀態(tài)碼和提示–可自己配

import axios from "axios"; import router from "./../router"; import { Message, Loading, MessageBox } from "element-ui";// 設(shè)置axios全局默認(rèn)的BASE-URL, 只要設(shè)置了全局的默認(rèn)base_url,以后的請(qǐng)求會(huì)自動(dòng)拼接上base_url // -------------------------------注意改成自己的公共url------------------------------------ axios.defaults.baseURL = "http://192.168.1.194/gateway"; axios.defaults.timeout = 10000;let loading;// 配置axios的請(qǐng)求攔截器-(每次在請(qǐng)求頭上攜帶后臺(tái)分配的token-后臺(tái)判斷token是否有效等問(wèn)題) axios.interceptors.request.use(config => {// 在發(fā)送請(qǐng)求之前做些什么// console.log('請(qǐng)求到了喲', config.headers.Authorization)// 如果有其他的特殊配置 只需要判斷config參數(shù) 設(shè)置即可let showLoading = true;if (config.loading === false) {showLoading = false;}if (showLoading) {loading = Loading.service({text: "加載中...",spinner: "el-icon-loading",background: "rgba(0, 0, 0, 0.08)"});}// 標(biāo)識(shí)系統(tǒng)為AJAX請(qǐng)求config.headers["X-Requested-With"] = "XMLHttpRequest";// 統(tǒng)一的給config設(shè)置 token-------------------------------注意獲取方法------------------------------------// config.headers.Authorization = JSON.parse(localStorage.getItem('token'))config.headers["Token"] = "97aa8f6b569648c78005240033aa0438";return config;},error => {// 對(duì)請(qǐng)求錯(cuò)誤做些什么return Promise.reject(error);} );// 響應(yīng)攔截器 與后端定義狀態(tài)是100時(shí)候是錯(cuò)誤 跳轉(zhuǎn)到登錄界面 axios.interceptors.response.use(response => {// 成功status:200 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么console.log("接口success", response);loading && loading.close();// 根據(jù)接口返回狀態(tài)碼 定義const { code, data, message } = response.data;if (code) {switch (code) {case 200:return { code, data };case 3012:return { code, data };case 404:Message({message: "網(wǎng)絡(luò)請(qǐng)求不存在",type: "error",duration: 2 * 1000});return Promise.reject({ code, data });case 100:localStorage.removeItem("token");router.push({path: "/login",querry: {} // 登錄過(guò)期 回到登錄頁(yè)});return Promise.reject({ code, data });case 4011:Message.closeAll();MessageBox.alert("登錄超時(shí)或身份失效,請(qǐng)重新登錄!", "警告", {customClass: "alertbox",confirmButtonText: "確定",type: "warning",center: true,callback: action => {// location.reload()router.push("/");}});return Promise.reject({ code, data });case 4002:default:Message({message: message || "Error",type: "error",duration: 5 * 1000});return Promise.reject({ code, data });}}// return response.data},error => {loading && loading.close();console.log("接口error", error, error.response);const { status } = error.response;switch (status) {case 500:Message.closeAll();Message({message: "請(qǐng)求超時(shí)",type: "error",duration: 3 * 1000});break;case 700:Message.closeAll();Message({message: "網(wǎng)絡(luò)中斷",type: "error",duration: 3 * 1000});break;default:Message({message: error.message,type: "error",duration: 3 * 1000});}// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么return Promise.reject(error);} );const $http = {};$http.get = function(url, data, config) {// 這一步把a(bǔ)pi方法里的 地址 參數(shù) 配置傳入進(jìn)來(lái) 配置到config 然后調(diào)用上面封裝的axiosconfig = config || {};config.url = url;config.method = "get";config.params = data;return axios.request(config); };$http.delete = function(url, data, config) {config = config || {};config.url = url;config.method = "delete";config.params = data;return axios.request(config); };$http.post = function(url, data, config) {config = config || {};config.url = url;config.method = "post";config.data = data;return axios.request(config); };$http.put = function(url, data, config) {config = config || {};config.url = url;config.method = "put";config.data = data;return axios.request(config); };export { axios, $http };

2.接口方法封裝 src/api/way.js:
①引入封裝的$http

②使用$http.get(url,data,config) ; 下方的函數(shù)方法都是可以接受三個(gè)參數(shù)的 分別是 地址 參數(shù) 配置 三個(gè)參數(shù)可以由組件內(nèi)使用的函數(shù)function傳入

③在組件內(nèi)使用,接受傳遞的參數(shù)和配置(詳見(jiàn)test.vue組件內(nèi)的方法)

以下get post put delete 請(qǐng)求均有;且對(duì)于不同的請(qǐng)求需要配置的config也有

import { $http } from '@/utils/request'// $http.get(url,data,config) // 下方的函數(shù)方法都是可以接受三個(gè)參數(shù)的 分別是 地址 參數(shù) 配置 三個(gè)參數(shù)可以由函數(shù)function傳入// 獲取詳情 export function getlist() {return $http.get(`main/queTactic/list`) } // 獲取班級(jí)列表 export function getClass(teacherId) {return $http.get(`/basis/teacher/queryTeacherClass/${teacherId}`) } // 獲取學(xué)科網(wǎng)url export function getUrl() {return $http.post(`/auth/api/authorize`) } // 獲取知識(shí)點(diǎn) export function getKnowledgeIdByChapterIds(data) {return $http.post(`/question/message/getKnowledgeIdByChapterIds`, data) } // 修改出題策略 export function editTactics(data) {return $http.put('main/queTactic', data) } // 個(gè)性化組題刪除題 export function indiviDelete(data) {return $http.delete(`/main/personal/deleteQuestionPersonalJob`, data) } // 特殊的傳參---------例如 文件流下載 需要設(shè)置配置responseType 否則下載的文件打開(kāi)不了----------- export function downloadExcel(examId) {return $http.get(`main/statistics/report/${examId}/export/questionExcel`, null, { responseType: 'blob' }) // 下方請(qǐng)求也可以 但是需要最上方import引入之前封裝的axios // return axios.request({ // url: `main/statistics/report/${examId}/export/questionExcel`, // responseType: 'blob', // method: 'get' // }) }

3.scr/views/test.vue在組件內(nèi)使用接口方法:
①引入way.js內(nèi)的接口方法:
②傳遞參數(shù)
③通過(guò).then()獲取使用

<template><div>接口返回參數(shù)<div>{{ data }}</div><!-- <el-input v-model="input" placeholder="請(qǐng)輸入內(nèi)容" /> --><button @click="getlistRequest">get 獲取列表</button><button @click="getClassRequest">get動(dòng)態(tài)參數(shù) 獲取班級(jí)</button><button @click="btnRequest">post點(diǎn)擊獲取url</button><button @click="getKnowledgeRequest">post傳參獲取知識(shí)點(diǎn)</button><button @click="downloadExcelRequest">get文件流下載 配置config</button></div> </template><script> // 引入接口方法 import { getlist, getUrl, getClass, getKnowledgeIdByChapterIds, downloadExcel } from '@/api/way.js' export default {data() {return {input: '',data: null}},methods: {getlistRequest() {getlist().then(res => {console.log(res.data)this.data = res.data})},getClassRequest() {const data = 1932115674972160getClass(data).then(res => {console.log(res.data)this.data = res.data})},btnRequest() {getUrl().then(res => { this.data = res.data })},getKnowledgeRequest() {const data = {chapterIds: [22394],schoolId: 39}getKnowledgeIdByChapterIds(data).then(res => {console.log(res.data)this.data = res.data})},downloadExcelRequest() {const data = 1943647285534911downloadExcel(data).then(res => {const type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'const blob = new Blob([res])const url = window.URL.createObjectURL(blob, { type: type })const a = document.createElement('a')a.href = urldocument.body.appendChild(a)a.download = '學(xué)情報(bào)告.xlsx'a.click()window.URL.revokeObjectURL(blob)a.remove()})}} } </script><style> </style>

4.頁(yè)面和接口展示:
成功200:

需要配置config的下載:

請(qǐng)求失敗提示:

總結(jié)

以上是生活随笔為你收集整理的vue项目请求封装;axios封装使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。