vue-axios使用详解

vue-axios

GET请求

?
1
2
3
4
5
axios.get( "/user?id=1" )
   .then( function (response){
   })
   . catch ( function (error){
   })

POST请求

?
1
2
3
4
5
6
7
8
9
10
axios.post( '/user' , {
   firstName: 'Fred' ,
   lastName: 'Flintstone'
  })
  .then( function (response) {
   console.log(response);
  })
  . catch ( function (error) {
   console.log(error);
  });

合并请求

?
1
2
3
4
5
6
7
8
9
10
11
12
function getUserAccount() {
  return axios.get( '/user/12345' );
}
 
function getUserPermissions() {
  return axios.get( '/user/12345/permissions' );
}
 
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread( function (acct, perms) {
   // Both requests are now complete
  }));

配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Qs from 'qs'
{
  //请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖掉config中的url
  url: '/user' ,
 
  // 请求方法同上
  method: 'get' , // default
  // 基础url前缀
  baseURL: 'https://some-domain.com/api/' ,
  
    
  transformRequest: [ function (data) {
   // 这里可以在发送请求之前对请求数据做处理,比如form-data格式化等,这里可以使用开头引入的Qs(这个模块在安装axios的时候就已经安装了,不需要另外安装)
  data = Qs.stringify({});
   return data;
  }],
 
  transformResponse: [ function (data) {
   // 这里提前处理返回的数据
 
   return data;
  }],
 
  // 请求头信息
  headers: { 'X-Requested-With' : 'XMLHttpRequest' },
 
  //parameter参数
  params: {
   ID: 12345
  },
 
  //post参数,使用axios.post(url,{},config);如果没有额外的也必须要用一个空对象,否则会报错
  data: {
   firstName: 'Fred'
  },
  auth: {
   username: 'janedoe' ,
   password: 's00pers3cret'
  },
  //设置超时时间
  timeout: 1000,
  //返回数据类型
  responseType: 'json' , // default
 
   .....等等
}

你可能感兴趣的:(vue.js)