vue3 actual axios request encapsulation problem
1. Create an http folder in the src directory, and create index.js, request.js, and api.js under the http folder
2. The role of index.js: used to export all interfaces defined by api.js, the code is as follows
export * from './api';
3. The request.js code is as follows:
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. the api.js code is as follows :
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. Call in the page
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 simple encapsulation tutorial
First create a new utils folder in the root directory, and create two new files below, requests .js and html.js
requests.js is used to introduce axios and set the root domain name and some default settings, interceptors, etc.
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
After writing, expose the created instance object and introduce it in html.js
The function of the html.js file is to call the instance object of requests and all access Store it in this file (api) and import it as needed when using it.
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)
Introduced files:
<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>
The above is the detailed content of How vue3 solves the axios request encapsulation problem. For more information, please follow other related articles on the PHP Chinese website!

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor
