Table of Contents
Introduction to Axios
Home Web Front-end Vue.js 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

Nov 23, 2022 pm 08:28 PM
vue axios

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
Copy after login
bower installation

bower install axios
Copy after login
Introduced through cdn

<script></script>
Copy after login

main.js file in the vue project Introduce axios

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

axios

<script>
	export default {
		mounted(){
			this.$axios.get(&#39;/goods.json&#39;).then(res=>{
				console.log(res.data);
			})
		}
	}
</script>
Copy after login

##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

<div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>

Method 2

<div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>

##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);
			})
Copy after login
Method 2

$axios({
	method: 'post',
	url: '/url',
	data: {
		id:1
	}
}).then(res=>{
	console.log(res.data);
},err=>{
	console.log(err);
})
Copy after login
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);
})
Copy after login

4, put and patch requestSample code

put request

this.$axios.put('/url',{
				id:1
			}).then(res=>{
				console.log(res.data);
			})
Copy after login
patch request

this.$axios.patch('/url',{
				id:1
			}).then(res=>{
				console.log(res.data);
			})
Copy after login

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);
			})
Copy after login
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);
})
Copy after login

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);
	})
)
Copy after login

四、Axios实例

1、创建axios实例

示例代码

let instance = this.$axios.create({
				baseURL: 'http://localhost:9090',
				timeout: 2000
			})
			
instance.get('/goods.json').then(res=>{
	console.log(res.data);
})
Copy after login

可以同时创建多个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';
Copy after login

3、axios实例配置

示例代码

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

4、axios请求配置

示例代码

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

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

五、拦截器

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

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
})
Copy after login

2、响应拦截器

示例代码

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

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

				return Promise.reject(err);
			})
Copy after login

3、取消拦截

示例代码

let instance = this.$axios.interceptors.request.use(config=>{
				config.headers = {
					token: ''
				}
				return config
			})
			
//取消拦截
this.$axios.interceptors.request.eject(instance);
Copy after login

六、错误处理

示例代码

this.$axios.get('/url').then(res={

			}).catch(err=>{
				//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
				console.log(err);
			})
Copy after login

七、取消请求

示例代码

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

(学习视频分享: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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles