给Vue原型挂载一个属性
Vue.prototype.$axios=Axios;
全局默认设置
Axios.defaults.baseURL='http://182.254.146.100/api'
post请求的时候,如果数据是字符串,默认头就是键值对
否则是对象,就是application json
this.$axios.get(url,options)
this.$axios.post(url,data,options)
//查询字符串
options:{params:{id:1},headers::{'content-type':'xxxxx'},baseURL:''}
get请求
发起个user请求,参数为指定的ID
axios.get('/user?ID=1234')
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
//上面的请求也可以选择下面的方式来写
axios.get('/user',{
params:{
ID:1234
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
发起一个POST请求
axios.post('/user',{
firstName:'firend',
lastName:'Flintstone'
content:'我要努力赶上她们的步伐'
},{
//设置
headers:{
'content-type':'application/x-www-form-urlencoded'
}
})
.then(function(response){
console.log(response);
}
.catch(function(error){
console.log(error);
})
export default{
data(){
return{
data:[]
}
},created(){
this.$axios.get('url')
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
}
}
axios合并请求:将两个请求一起发送,只要有一个失败就算失败,成功只有全体成功
created(){
this.$axios.all([
this.$axios.post('postcomment/300','content=123');
this.$axios.get('getcomments/300?pageindex=1');
])
分发响应
.then(this.$axios.spread(getMsg))
.catch(err=>{
console.log(err);
})
function getMsg(res1,res2){
console.log(res1);
console.log(res2);
}
}
axios.all([请求1,请求2])
分发响应 axios.spread(fn)
fn:对应参数(res)和请求的顺序一致
应用场景:
必须保证两次请求都成功,比如,分头获取省市的数据
执行特点:只要有一次失败就算失败,否则成功
环境上报错:把原来的环境配置拿过来,基本上就不会出问题了的
//给Vue原型挂载一个属性
Vue.prototype.$axios=Axios;
拦截器:相当于过滤的行为,在一次请求与响应中,添油加醋
axios.interceptor.request.use(fn) 在请求之前
function(config){ config相当于options对象
config.headers={xxx}
}
Axios.defaults.baseURL='http://182.254.146.100:8890/api/';
//拦截器
Axios.interceptors.request.use(function(config){
console.log(config);
return config; //返回没有修改的设置
})
默认设置
Axios.default.headers={
accept:'defaults'
}
Axios.interceptors.request.use(function(config){
console.log(config);
return config; return false;
config.headers.accept:'interceptors';
config.headers={
accept:'interceptors'
}
return config;
})
this.$axios.get('url')
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
vue2.0入门及实战开发(九)
猜你喜欢
转载自blog.csdn.net/a3060858469/article/details/80607400
今日推荐
周排行