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';
•get request
axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
依赖于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)
Complete The request should also include .then and .catch
.then(function(res){ console.log(res) }) .catch(function(err){ console.log(err) })
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))
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!