


Let's talk about how to use axios in vue project in this article? Basic usage sharing
Tip: This article explains in detail the examples of axios in the vue project. When using the Vue.js framework to develop front-end projects, ajax requests are often sent to the server interface. During the development process, axios needs to be further encapsulated to facilitate use in the project. [Learning video sharing: vue video tutorial, web front-end video]
Introduction to Axios
##axios framework Full name (ajax - I/O - system):
- http client based on
- promise
for browsers and
node.js, Therefore, you can use Promise API
1. What does axios do
Speaking ofaxiosWe have to talk about
Ajax. When the old browser page requests data from the server, because the data of the entire page is returned, the page will be forced to refresh, which is not very user-friendly. And we only need to modify part of the data on the page, but the data of the entire page is sent from the server, which consumes a lot of network resources. We only need to modify some data on the page, and we also hope not to refresh the page, so asynchronous network requests come into being.
Ajax(Asynchronous JavaScript and XML): Asynchronous network request. Ajax allows the page to request data without refreshing.
- The configuration and calling methods of native XMLHttpRequest are very cumbersome, and it is very troublesome to implement asynchronous requests.
- jQuery's ajax is very different from native ajax. Easy to use, but there is no need to reference the jQuery framework because you want to use ajax asynchronous network requests
Axios (ajax i/o system): This is not a new The technology is essentially an encapsulation of native XMLHttpRequest, which can be used in browsers and nodejs HTTP clients, but it is based on Promise and complies with the latest ES specifications. Has the following characteristics:
- Create XMLHttpRequest request in the browser
- Send http request in node.js
- Support Promise API
- Interception Requests and Responses
- Convert request and response data
- Cancel request
- Automatically convert JSON data
- Client support to prevent CSRF/XSRF (cross Domain request forgery)
2. Installation and use
There are three types of installation Method: npm installationnpm install axiosbower installation
bower install axiosIntroduced through cdn
<script></script>
main.js file in the vue project Introduce
axios
import axios from 'axios' Vue.prototype.$axios = axiosin the component and use
axios
<script> export default { mounted(){ this.$axios.get('/goods.json').then(res=>{ console.log(res.data); }) } } </script>
##3. Axios request method
1. Methods that axios can request:
get: Get data and request the specified Information, returns the entity object- post: Submit data to the specified resource (such as form submission or file upload)
- put: Update data, the data transmitted from the client to the server replaces the specified document Content
- patch: update data, which is a supplement to the put method and is used to locally update known resources
- delete: request the server to delete the specified data
Method 1
<pre class="brush:php;toolbar:false"> //请求格式类似于 http://localhost:8080/goods.json?id=1
this.$axios.get('/goods.json',{
params: {
id:1
}
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})</pre>
<pre class="brush:php;toolbar:false">this.$axios({
method: 'get',
url: '/goods.json',
params: {
id:1
}
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})</pre>
##3. Post requestPost requests are generally divided into two types
1,form-data
Form submission, this type is more commonly used when uploading pictures and files 2. application/ json
is generally used for ajax asynchronous requestsSample code
Method one
this.$axios.post('/url',{ id:1 }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
Method 2
$axios({ method: 'post', url: '/url', data: { id:1 } }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
form-data request
let data = { //请求参数 } let formdata = new FormData(); for(let key in data){ formdata.append(key,data[key]); } this.$axios.post('/goods.json',formdata).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
4, put and patch requestSample code
put request
this.$axios.put('/url',{ id:1 }).then(res=>{ console.log(res.data); })
patch request
this.$axios.patch('/url',{ id:1 }).then(res=>{ console.log(res.data); })
5. Delete requestSample code
Parameters are in plain text Submit in the form
this.$axios.delete('/url',{ params: { id:1 } }).then(res=>{ console.log(res.data); })
Parameters are submitted in the form of encapsulated objects
this.$axios.delete('/url',{ data: { id:1 } }).then(res=>{ console.log(res.data); }) //方法二 axios({ method: 'delete', url: '/url', params: { id:1 }, //以明文方式提交参数 data: { id:1 } //以封装对象方式提交参数 }).then(res=>{ console.log(res.data); })
6. Concurrent requestsConcurrent requests: Make multiple requests at the same time and process the return values uniformly
Sample code
this.$axios.all([ this.$axios.get('/goods.json'), this.$axios.get('/classify.json') ]).then( this.$axios.spread((goodsRes,classifyRes)=>{ console.log(goodsRes.data); console.log(classifyRes.data); }) )
四、Axios实例
示例代码
let instance = this.$axios.create({ baseURL: 'http://localhost:9090', timeout: 2000 }) instance.get('/goods.json').then(res=>{ console.log(res.data); })
可以同时创建多个axios实例。
axios实例常用配置:
- baseURL 请求的域名,基本地址,类型:String
- timeout 请求超时时长,单位ms,类型:Number
- url 请求路径,类型:String
- method 请求方法,类型:String
- headers 设置请求头,类型:Object
- params 请求参数,将参数拼接在URL上,类型:Object
- data 请求参数,将参数放到请求体中,类型:Object
示例代码
//配置全局的超时时长 this.$axios.defaults.timeout = 2000; //配置全局的基本URL this.$axios.defaults.baseURL = 'http://localhost:8080';
示例代码
let instance = this.$axios.create(); instance.defaults.timeout = 3000;
示例代码
this.$axios.get('/goods.json',{ timeout: 3000 }).then()
以上配置的优先级为:请求配置 > 实例配置 > 全局配置
五、拦截器
拦截器:在请求或响应被处理前拦截它们
示例代码
this.$axios.interceptors.request.use(config=>{ // 发生请求前的处理 return config },err=>{ // 请求错误处理 return Promise.reject(err); }) //或者用axios实例创建拦截器 let instance = $axios.create(); instance.interceptors.request.use(config=>{ return config })
示例代码
this.$axios.interceptors.response.use(res=>{ //请求成功对响应数据做处理 return res //该返回对象会传到请求方法的响应对象中 },err=>{ // 响应错误处理 return Promise.reject(err); })
示例代码
let instance = this.$axios.interceptors.request.use(config=>{ config.headers = { token: '' } return config }) //取消拦截 this.$axios.interceptors.request.eject(instance);
六、错误处理
示例代码
this.$axios.get('/url').then(res={ }).catch(err=>{ //请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象 console.log(err); })
七、取消请求
示例代码
let source = this.$axios.CancelToken.source(); this.$axios.get('/goods.json',{ cancelToken: source }).then(res=>{ console.log(res) }).catch(err=>{ //取消请求后会执行该方法 console.log(err) }) //取消请求,参数可选,该参数信息会发送到请求的catch中 source.cancel('取消后的信息');
The above is the detailed content of Let's talk about how to use axios in vue project in this article? Basic usage sharing. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.


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

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

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
