vue3實戰(zhàn)-axios請求封裝問題(get、post、put、delete)
vue3實戰(zhàn)axios請求封裝問題
1、在src目錄下創(chuàng)建http文件夾,在http文件夾下分別創(chuàng)建index.js、request.js、api.js
2、index.js的作用:用于導出api.js定義的所有接口,代碼如下
export * from './api';
3、request.js代碼如下:
import axios from 'axios'; import buildURL from 'axios/lib/helpers/buildURL'; import { merge } from 'axios/lib/utils'; //判斷指定參數(shù)是否是一個純粹的對象,所謂"純粹的對象",就是該對象是通過"{}"或"new Object"創(chuàng)建的 function isPlainObject (val) { ? ?? ?return val && val.constructor.name === 'Object' } //請求之前進行攔截,可做的操作:1、添加loading的加載;2、添加請求頭;3、判斷表單提交還是json提交 let requestInterceptors = [ ?? ?config => { ?? ??? ?//添加loading的加載 ?? ??? ? ?? ??? ?//添加請求頭 ?? ??? ?config.headers.authorization = sessionStorage.getItem('Token'); ?? ??? ?//判斷表單提交還是json提交 ?? ??? ?if (config.emulateJSON && isPlainObject(config.data)) { ?? ??? ??? ?config.data = buildURL('', config.data).substr(1); ?? ??? ?} ?? ??? ?return config; ?? ?} ] //請求響應之后進行攔截,可做操作:1、取消loading的加載;2、對返回狀態(tài)進行判斷:如請求錯誤、請求超時、獲取數(shù)據(jù)失敗、暫無數(shù)據(jù)等等 let responseInterceptors = [ ?? ?res => { ?? ??? ?//取消loading加載 ?? ??? ? ?? ??? ?//對返回狀態(tài)進行判斷:如請求錯誤、請求超時、獲取數(shù)據(jù)失敗等等 ?? ??? ?//返回結果 ?? ??? ?return Promise.resolve(res); ?? ?}, ?? ?err => { ?? ??? ?//取消loading加載 ?? ??? ? ?? ??? ?//對返回狀態(tài)進行判斷:如請求錯誤、請求超時、獲取數(shù)據(jù)失敗等等 ?? ??? ?//返回結果 ?? ??? ?return Promise.reject(err); ?? ?} ] //組裝請求 let serviceCreate = config => { ?? ?let service = axios.create(merge({}, config)); ?? ?service.interceptors.request.use(...requestInterceptors); ?? ?service.interceptors.response.use(...responseInterceptors); ?? ?return service } serviceCreate(); export { serviceCreate, merge };
4、api.js代碼如下:
import { serviceCreate, merge } from '@/http/request'; //這種方式可以采用單個項目的接口,也可以使用多個項目的接口,看自己的項目情況而定 let http0 = serviceCreate({ ? ? baseURL: '/project1/api1', ? ? timeout: 15000,//請求超時 ? ? emulateJSON: true,//默認表單提交 }) let http1 = serviceCreate({ ? ? baseURL: '/project2/api2', ? ? timeout: 15000,//請求超時 ? ? emulateJSON: true,//默認表單提交 }) //get請求示例 export function getData(params, config) { ? ? return http0.get('/project/list', merge(config, { params })); } //delete請求示例 export function deleteData(params, config) { ? ? return http0.delete('/project/list', merge(config,{ params })); } //post請求示例(表單提交) export function postDataFrom(params, config) { ? ? return http0.post('/project/list', params, config); } //post請求示例(json提交) export function postDataJson(params, config) { ? ? return http0.post('/project/list', params, merge(config, { emulateJSON: false })); } //put請求示例(表單提交) export function putDataFrom(params, config) { ? ? return http0.put('/project/list', params, config); } //put請求示例(json提交) export function putDataJson(params, config) { ? ? return http0.put('/project/list', params, merge(config, { emulateJSON: false })); }
5、頁面中調用
import { getData, deleteData, postDataFrom, postDataJson, putDataFrom, putDataJson } from "@/http"; getData({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) }) deleteData({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) }) postDataFrom({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) }) postDataJson({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) }) putDataFrom({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) }) putDataJson ({ name: "我是參數(shù)" }).then(res => { console.log("返回數(shù)據(jù)", res) })
vue3 axios簡易封裝教程
首先在根目錄下新建utils文件夾,并在下面新建兩個文件,requests.js和html.js
requests.js用于引入axios并設置根域名以及一些默認設置、攔截器等。
import axios from "axios"; const service = axios.create({ baseURL: 'http://localhost:3000', timeout: 10000, }) // 請求攔截器 service.interceptors.request.use(config=>{ return config },err=>{ return Promise.reject(err) //返回錯誤 }) // 響應攔截器 service.interceptors.response.use(res=>{ return res },err=>{ return Promise.reject(err) //返回錯誤 }) export default service
寫完之后將創(chuàng)建的實例對象暴露出去,在html.js中進行引入
html.js文件的作用是調用requests的實例對象,并將所有的訪問均存放在這個文件中(api),使用的時候按需引入即可。
import request from "./requests"; export const GetPosts = () => request.get('posts/1') export const GetsearchData = (params) => request.get('/list',{params}) export const PostPosts = (params) => request.post('posts',params)
引入的文件:
<template> <el-button type="primary" @click="clickGet">點我發(fā)送get請求</el-button> <el-button type="primary" @click="clickPost">點我發(fā)送post請求</el-button> <el-button type="primary" @click="clickPut">點我發(fā)送put請求</el-button> <el-button type="primary" @click="clickDel">點我發(fā)送delete請求</el-button> </template> <script> import { GetPosts, PostPosts } from "../../utils/html" export default { setup(){ function clickGet(){ GetPosts().then(res => { console.log(res) }) // axios({ // method: 'GET', // url: 'http://localhost:3000/posts' // }).then(res => { // console.log(res) // }) } function clickPost(){ PostPosts({ title: '我超級喜歡打游戲', author: '賬本兒erer', age: '24' }).then(res => { console.log(res) }) } function clickPut(){ } function clickDel(){ } return { clickDel, clickGet, clickPost, clickPut } } } </script> <style> </style>
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue組件定義,全局、局部組件,配合模板及動態(tài)組件功能示例
這篇文章主要介紹了vue組件定義,全局、局部組件,配合模板及動態(tài)組件功能,結合實例形式分析了vue.js中組件的定義、全局組件、局部組件、配合模板組件及動態(tài)組件的相關使用方法與操作注意事項,需要的朋友可以參考下2019-03-03vue中el-select 和el-tree二次封裝實現(xiàn)
本文介紹了vue中el-select 和el-tree二次封裝實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-11-11vue后臺項目如何使用router.addRoutes動態(tài)加入路由的思路
這篇文章主要介紹了vue后臺項目如何使用router.addRoutes動態(tài)加入路由的思路,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06vue2利用html2canvas+jspdf動態(tài)生成多頁PDF方式
利用vue2結合html2canvas和jspdf,可以實現(xiàn)前端頁面內容導出為PDF的功能,首先需要安裝相關依賴,使用html2canvas將指定div內容捕捉為圖像,再通過jspdf將圖像轉換為PDF2024-09-09vue3中WatchEffect高級偵聽器的實現(xiàn)
本文主要介紹了vue3中WatchEffect高級偵聽器的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-01-01