Home  >  Article  >  Web Front-end  >  Let's talk about how to use axios in vue project in this article? Basic usage sharing

Let's talk about how to use axios in vue project in this article? Basic usage sharing

青灯夜游
青灯夜游forward
2022-11-23 20:28:322976browse

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

Lets talk about how to use axios in vue project in this article? Basic usage sharing

1. What does axios do

Speaking of

axiosWe 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.

There are many ways to implement ajax, such as jQuery-encapsulated ajax, native XMLHttpRequest, and axios. But all methods have advantages and disadvantages:

    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)

Lets talk about how to use axios in vue project in this article? Basic usage sharing

2. Installation and use

There are three types of installation Method:

npm installation

 npm install axios
bower installation

bower install axios
Introduced through cdn

<script></script>

main.js file in the vue project Introduce axios

import axios from 'axios'
Vue.prototype.$axios = axios
in the component and use

axios

<script>
	export default {
		mounted(){
			this.$axios.get(&#39;/goods.json&#39;).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

2. Get request

Sample code

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=&gt;{ console.log(res.data); },err=&gt;{ console.log(err); })</pre>

Method 2

<pre class="brush:php;toolbar:false">this.$axios({ method: 'get', url: '/goods.json',      params: {             id:1         } }).then(res=&gt;{ console.log(res.data); },err=&gt;{ 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 requests
Sample 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实例

1、创建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

2、axios全局配置

示例代码

//配置全局的超时时长
this.$axios.defaults.timeout = 2000;
//配置全局的基本URL
this.$axios.defaults.baseURL = 'http://localhost:8080';

3、axios实例配置

示例代码

let instance = this.$axios.create();
instance.defaults.timeout = 3000;

4、axios请求配置

示例代码

this.$axios.get('/goods.json',{
				timeout: 3000
			}).then()

以上配置的优先级为:请求配置 > 实例配置 > 全局配置

五、拦截器

拦截器:在请求或响应被处理前拦截它们

1、请求拦截器

示例代码

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
})

2、响应拦截器

示例代码

this.$axios.interceptors.response.use(res=>{
				//请求成功对响应数据做处理

				return res //该返回对象会传到请求方法的响应对象中
			},err=>{
				// 响应错误处理

				return Promise.reject(err);
			})

3、取消拦截

示例代码

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('取消后的信息');

(学习视频分享:web前端开发编程基础视频

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete