Home >Web Front-end >JS Tutorial >Ajax requests and axios packages are perfectly handled in vue

Ajax requests and axios packages are perfectly handled in vue

php中世界最好的语言
php中世界最好的语言Original
2018-04-27 16:09:511979browse

This time I will bring you the perfect processing of ajax requests and axios packages in vue. What are the precautions for handling ajax requests and axios packages in vue. The following is a practical case, let's take a look.

In vue, data requests are often used. Commonly used ones are: vue-resourse, axios

Today I am talking about the post request of axios

github source file and document address: [https://github.com/axios/axios]

First, introduce axios

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

•get request

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

•post request

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

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)

The complete request should also include .then and .catch

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

When the request is successful, Will execute .then, otherwise execute .catch

These two callback functions have their own independent scopes. If you access this directly inside, you cannot access the Vue instance

At this time, just add a .bind(this) to solve this problem

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

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

Recommended reading:

node implements the image verification code function during login

The vue parent component passes the value to the parent component Detailed explanation of steps

The above is the detailed content of Ajax requests and axios packages are perfectly handled in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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