Home > Web Front-end > JS Tutorial > How to use ajax request and axios package in vue

How to use ajax request and axios package in vue

php中世界最好的语言
Release: 2018-06-02 14:40:16
Original
1123 people have browsed it

This time I will show you how to use ajax requests and axios packages in vue. What are the precautions for using ajax requests and axios packages in vue. The following is a practical case, let's take a look.

First, introduce axios

CDN: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm: npm install axios   并在全局的js中引入:import axios from 'axios';
Copy after login

•get request

axios.get('/user?ID=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
Copy after login

post request

 依赖于qs包,将对象转换成以&连接的字符串
//例:
axios.post( postUrl ,qs.stringify({userid:1,username:'yyy'})).then(function (response) {
  console.log(response);
})
Copy after login

Appendix: Configuring axios

In the above encapsulated method, three configuration items of axios are used. In fact, Only the url is required. For the complete api, please refer to the instructions for use.

For convenience, axios also has aliases for each method. For example, the saveForm method above is equivalent to:

axios.post('/user', context.state.test02)
Copy after login

Complete The request should also include .then and .catch

.then(function(res){
 console.log(res)
})
.catch(function(err){
 console.log(err)
})
Copy after login

When the request is successful, .then will be executed, otherwise .catch

These two callback functionshave their own Independent scope, if you access this directly inside, you cannot access the Vue instance

At this time, you only need to add a .bind(this) to solve this problem

.then(function(res){
 console.log(this.data)
}.bind(this))
Copy after login

I believe you have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use vue source code to parse the event mechanism

How to operate JS to obtain the city and geographical location of the user

The above is the detailed content of How to use ajax request and axios package in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template