vue3怎么解决axios请求封装问题
vue3实战axios请求封装问题
1、在src目录下创建http文件夹,在http文件夹下分别创建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'; //判断指定参数是否是一个纯粹的对象,所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的 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、对返回状态进行判断:如请求错误、请求超时、获取数据失败、暂无数据等等 let responseInterceptors = [ res => { //取消loading加载 //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等 //返回结果 return Promise.resolve(res); }, err => { //取消loading加载 //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等 //返回结果 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: "我是参数" }).then(res => { console.log("返回数据", res) }) deleteData({ name: "我是参数" }).then(res => { console.log("返回数据", res) }) postDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) }) postDataJson({ name: "我是参数" }).then(res => { console.log("返回数据", res) }) putDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) }) putDataJson ({ name: "我是参数" }).then(res => { console.log("返回数据", 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
写完之后将创建的实例对象暴露出去,在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">点我发送get请求</el-button> <el-button type="primary" @click="clickPost">点我发送post请求</el-button> <el-button type="primary" @click="clickPut">点我发送put请求</el-button> <el-button type="primary" @click="clickDel">点我发送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>
以上是vue3怎么解决axios请求封装问题的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

在Vue应用中使用axios是十分常见的,axios是一种基于Promise的HTTP客户端,可以用于浏览器和Node.js。在开发过程中,有时会出现“Uncaught(inpromise)Error:Requestfailedwithstatuscode500”的错误提示,对于开发者来说,这个错误提示可能有些难以理解和解决。本文将会探讨这

最近,在使用Vue应用开发过程中,我遇到了一个常见的问题:“TypeError:Failedtofetch”错误提示。这个问题出现在使用axios进行HTTP请求时,后端服务器没有正确响应请求时发生。这种错误提示通常表明请求无法到达服务器,可能是由于网络原因或服务器未响应造成的。出现这个错误提示后,我们应该怎么办呢?以下是一些解决方法:检查网络连接由于

在Vue应用中使用axios时出现“Error:NetworkError”怎么解决?在Vue应用的开发中,我们经常会使用到axios进行API的请求或数据的获取,但是有时我们会遇到axios请求出现“Error:NetworkError”的情况,这时我们该怎么办呢?首先,需要了解“Error:NetworkError”是什么意思,它通常表示网络连

高效利用Vue和Axios实现前端数据的批量处理在前端开发中,数据的处理是一个常见的任务。当我们需要处理大量数据时,如果没有有效的方法,处理数据将会变得十分繁琐和低效。Vue是一种优秀的前端框架,而Axios是一个流行的网络请求库,它们可以协同工作来实现前端数据的批量处理。本文将详细介绍如何高效利用Vue和Axios来进行数据的批量处理,并提供相关的代码示例

Vue实现文件上传的完整指南(axios、element-ui)在现代Web应用程序中,文件上传已经成为一项基本的功能。无论是上传头像、图片、文档或者视频,我们都需要一个可靠的方法来将文件从用户的计算机上传到服务器中。本文将为您提供一份详细的指南,介绍如何使用Vue、axios和element-ui来实现文件上传。什么是axiosaxios是一个基于prom

Vue中数据请求的选择:AxiosorFetch?在Vue开发中,处理数据请求是一个非常常见的任务。而选择使用哪种工具来进行数据请求,则是一个需要考虑的问题。在Vue中,最常见的两种工具是Axios和Fetch。本文将会比较这两种工具的优缺点,并给出一些示例代码来帮助你做出选择。Axios是一个基于Promise的HTTP客户端,可以在浏览器和Node.

使用Vue构建自定义元素WebComponents是一组web原生API的统称,允许开发者创建可复用的自定义元素(customelements)。自定义元素的主要好处是,它们可以在使用任何框架,甚至是在不使用框架的场景下使用。当你面向的最终用户可能使用了不同的前端技术栈,或是当你希望将最终的应用与它使用的组件实现细节解耦时,它们会是理想的选择。Vue和WebComponents是互补的技术,Vue为使用和创建自定义元素提供了出色的支持。你可以将自定义元素集成到现有的Vue应用中,或使用Vue来构

在Vue应用中使用axios时出现“Error:timeoutofxxxmsexceeded”怎么办?随着互联网的快速发展,前端技术也在不断地更新迭代,Vue作为一种优秀的前端框架,近年来受到大家的欢迎。在Vue应用中,我们常常需要使用axios来进行网络请求,但是有时候会出现“Error:timeoutofxxxmsexceeded”的错误
