vue中的axios与promise

以公共组件实例说明。

子组件son:

1
2
3
4
<button @click="getData"></button>
getData(){
this.$emit('getData');
}

父组件
1
2
3
4
5
6
7
8
<son @getData='getData'></son>
<div></div>//获取的数据显示在这里

getData(){
axios.get('url').then((res)=>{
this.here = res;
})
}

结论:axios请求放在父组件中,通过触发子组件中的自定义事件来实现。

由于axios请求多的话,参数中会有不少重复的,故可单独建立config.js

1
2
3
4
5
6
7
8
9
10
11
export default {
method: 'get',
url: 'localhost:6666',
headers: {
token: 'ftv1443qby6bdfa41t90sfvq89hg3h54u989m9imog79g4'
},
data: {
id: 666,
name: 'ColMugX'
}
}
1
2
3
4
5
6
7
8
9
10
11
12
//主文件中引入
import axios from 'axios'
import config from './config'

let conf = config;
conf.url = '';//修改与配置不同的配置
//此处可以使用请求拦截器
/*axios.interceptors.request.use((config)=>{
config.url = '';
return config;
})*/
axios(config).then(...)

post请求引入qs对编码进行格式化,处理url查询参数,如axios.post(‘foo’,qs.stringify(config.data))

axios同时执行多个请求(类似promise)

1
2
3
4
5
6
7
8
9
10
function A(){
return axios.get('');
}
function B(){
return axios.post('','');
}
axios.all([A(),B()])
.then(axios.spread((res1,res2)=>{
//对两个数据进行相应处理
}))

二次封装

目的:配置项独立(config.js)、错误统一处理、接口统一归类(api.js)

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
47
48
49
50
51
52
53
54
55
//axios封装为fetch,直接取链接就好 
//axio.js
import config from 'config.js'
//加个拦截器处理请求和响应
axios.interceptors.response.use(
response => {
return response
},
error => {
if(error.response){
switch (error.response.status){
case 404:
console.log('request 404');
break
case 500:
console.log('request 500')
break
}
}
console.log(error);
return Promise.reject({code:'-100',message:'wait'})
}
)
//封装请求并暴露出来
export function fetch(url,options) {
var opt = options||{}
return new Promise((resolve,reject)=>{
axios({
method:opt.type || 'get',
url: url,
params: opt.params || {},
// 判断是否有自定义头部,以对参数进行序列化。不定义头部,默认对参数序列化为查询字符串。
data: (opt.headers ? opt.data : stringify(opt.data)) || {},
responseType: opt.dataType || 'json',
// 设置默认请求头
headers: opt.headers || {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(res => {
if(res.data.code===0){
rersolve(res.data)
}else if(res.data.code==='000'){
resolve(res.data)
}else{
reject(res.data)
}
})
.catch(error=>{
console.log(error)
})
})
}
export default axios
//父组件中调用时
fetch('url',{}).then()
//options可选,比如请求类别等均可在调用时覆盖