4 Vue-Resource & Axios
4.1 Vue-Resource基础介绍
sdn方式加载 vue-resource.min.js
通过npm的方式:npm install vue-resource --save
vue-resource 的请求API是按照REST风格设计的,它提供了7种请求API:get、head、delete、jsonp、post、put、patch
全局拦截器 interceptors
Get:
get:function () {
this.$http.get("package.json",{
params:{
uesrId:"101"
},
headers:{
token:"abcd"
}
}).then(res=>{
this.msg = res.data;
},error=>{
this.msg = error;
});
},
Post:
post:function () {
this.$http.post("package.json",{
userId:"102"
},{
headers:{
access_token:"abc"
}
}).then(function (res) {
this.msg = res.data;
});
},
JSONP:
jsonp:function () {
this.$http.jsonp("http://www.imooc.com/course/AjaxCourseMenbers?ids=796").then(function (res) {
this.msg = res.data;
});
}
类似于Ajax的请求方式Http:
http:function () {
this.$http({
url:"package.json",
method:"get",
params:{
userId:"103"
},
headers: {
token: "123"
},
timeout:5,
before:function () {
console.log("before init.");
}
}).then(function (res) {
this.msg = res.data;
});
}
Interceptors:
mounted:function(){
Vue.http.interceptors.push(function (request,next) {
console.log("request init.");
next(function (response) {
console.log("response init.");
return response;
})
})
},
4.2 Axios 基础介绍
cdn引用axios
npm install axios --save
axios提供了将近8个API:request、get、delete、head、options、post、put、patch。
Get:
get:function () {
axios.get("../package.json",{
params:{
userId:"999"
},
headers:{
token:"jack"
}
}).then(res =>{
this.msg = res.data;
}).catch(function (error) {
console.log("error:"+error)
})
},
Post:
post:function () {
axios.post("../package.json",{
userId:"888"
},{
headers:{
token:"Tom"
}
}).then(res=>{
this.msg = res.data;
}).catch(error=>{
console.log("error:"+error);
})
}
Http:
注:post发送的是request的body,get是发送的request的params。所以数据传送的时候post用data,get用params。
http:function () {
axios({
url:"../package.json",
method:"post",
params:{
userId:"get"
},
data:{
userId:"post"
},
headers:{
token:"http-token"
}
}).then(res=>{
this.msg = res.data;
})
}
Interceptors: request在请求之前拦截,response在返回数据的时候拦截
mounted:function(){
axios.interceptors.request.use(function (request) {
console.log("request init.");
return request;
})
axios.interceptors.response.use(function (response) {
console.log("response init.")
return response;
})
},