This article brings you a basic introduction to axios packaging in Vue (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Axios is a promise-based HTTP library that can be used in browsers and node.js. Using axios in a vue project is a very wise choice, because vue officials have announced that they will no longer maintain vue-resource, and recommend the use of axios.
1 Why choose axios?
Use axios to perform unified request-response interception. For example, when responding, we intercept the response information, determine the status code, and pop up the error message
Set the request timeout, for example, stop the request if there is no response after 3000ms
Based on promise, you can easily use then or catch to process the request
Automatically convert json data
#2 How to use?
You can use the following methods
1. npm install axios --save 2. bower install axios --save 3. <script></script>
3 to encapsulate http requests
The example given by the official website:
axios.get('/user?ID=12345') .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });
On this basis we should encapsulate post get in http again For the put delete method, you only need to call the interface function and pass in params on the specific page. We should encapsulate the rest such as url, header and so on.
For example, use a function in index.vue to obtain the corresponding user information through id, and return the result in the result of the then method
API.getUserInfo({id:'01'}).then((result)=>{})
4 Implementation idea
Create a new file, Construct an axios object instance such as axios.js
import axios from 'axios'; import router from '../router'; // 创建axios实例 const service = axios.create({ timeout: 30000 // 请求超时时间 }) // 添加request拦截器 service.interceptors.request.use(config => { return config }, error => { Promise.reject(error) }) // 添加respone拦截器 service.interceptors.response.use( response => { let res={}; res.status=response.status res.data=response.data; return res; }, error => { if(error.response && error.response.status == 404){ router.push('/blank.vue') } return Promise.reject(error.response) } ) export function get(url, params = {}) { params.t = new Date().getTime(); //get方法加一个时间参数,解决ie下可能缓存问题. return service({ url: url, method: 'get', headers: { }, params }) } //封装post请求 export function post(url, data = {}) { //默认配置 let sendObject={ url: url, method: 'post', headers: { 'Content-Type':'application/json;charset=UTF-8' }, data:data }; sendObject.data=JSON.stringify(data); return service(sendObject) } //封装put方法 (resfulAPI常用) export function put(url,data = {}){ return service({ url: url, method: 'put', headers: { 'Content-Type':'application/json;charset=UTF-8' }, data:JSON.stringify(data) }) } //删除方法(resfulAPI常用) export function deletes(url){ return service({ url: url, method: 'delete', headers: {} }) } //不要忘记export export { service }
The above code mainly implements a basic axios encapsulation, and obtains the response object when the request is successful. We mainly need to obtain several useful information, such as status code, data That's it, handle errors at the same time, for example, return 404 and we jump to a new interface
Encapsulation interface function
Create a new file, such as api.js
import {get, post,deletes,put} from './axios.js' ;//导入axios实例文件中方法 let bsae_api = process.env.BASE_API ? './'+process.env.BASE_API :'..' //获取项目api请求地址 //根据id获取用户信息 export const getUserInfoById=(id)=>{ return get(`${bsae_api}/web/user/${id}`); //resfulapi风格 }
For specific pages, use index.vue
import API from '@/utils/api' getUserInfo(){ API.getUserInfoById('01).then((result)=>{ }).catch((error)=>{ }) }
The above is some basic introduction to axios packaging
Related recommendations:
axios encapsulation fetch call details
The above is the detailed content of Basic introduction to axios packaging in vue (with code). For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
