3-1 vue-resource基础介绍

时间:2022-01-22 10:00:24

1.静态引用

<script src="https://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.js"></script>

2.npm方式安装(推荐)

$ npm install vue-resource --save
-save 是指将包信息添加到 package.json 里的dependencies节点,表示发布时依赖的包。
-save-dev 是指将包信息添加到 package.json 里的 devDependencies节点,表示开发时依赖的包。

3.七种请求API  (详细介绍 : https://www.npmjs.com/package/vue-resource

1.this.$http.get(url, [options]);
2.this.$http.head(url, [options]);
3.this.$http.delete(url, [options]);
4.this.$http.jsonp(url, [options]);
5.this.$http.post(url, [body], [options]);
6.this.$http.put(url, [body], [options]);
7.this.$http.patch(url, [body], [options]);

4.参数

url          ==> 请求URL
method ==> 请求HTTP方式
body ==> request body
params ==> 请求的URL参数对象
headers ==> request header(第三方请求头注入的参数)
timeout ==> 超时(0表示无超时时间)
before ==> 请求发送前的处理函数
progress ==> ProgressEvent回调处理函数
credientials ==> 表示跨域请求是否需要使用凭证
emulateHTTP ==> 发送PUT, PATCH, DELETE请求时以HTTP Post的方式发送, 并设置请求头的X-HTTP-Method-Override
emulateJSON ==> 将request body以application/x-www-form-urlencoded content type发送

二.以下几种请求

1.Get请求

new Vue({
methods: {
// http://192.168.17.112:8010/AlanMall/package.json?userId=101
get: function(){
this.$http.get("package.json", {
// 参数一定写在params里
params: {
userId: "101"
},
// 请求头
headers: {
token: "adcd"
}
}).then(res => {
this.msg = res.data;
}, error => {
this.msg = error;
});
}
}
})

2.Post请求

methods: {
// http://192.168.17.112:8010/AlanMall/package.json?userId=101
post: function(){
this.$http.post("package.json", {
userId: "102"
},{
headers: {
access_token: "post"
}
}).then(function(res){
this.msg = res.data;
}, function(res){
this.msg = res.data;
});
}
}

3.JSONP请求

methods: {
jsonp: function(){
// http://www.imooc.com/course/AjaxCourseMembers?ids=796
this.$http.jsonp("http://taoalan.com/json/alan.php", {
jsonpCallback: "flightHandler"
}).then(res =>{
this.msg = res.data;
}, error =>{
this.msg = error
});
}
}

要求传送的参数中一定要有特定的函数名,可以这样设置:
jsonp设置的是传callback的参数名,jsonpCallback是返回的函数名

this.$http.jsonp(url, {
params:params,
jsonp: 'callBackParam',
jsonpCallback: "getCallBack"
})

4.vue-resource底层http

new Vue({
methods: {
this.$http({
url: "package.json",
params: {
urseId: "103",
},
headers: {
token: "basehttp"
},
timeout: 5,
before: function(){
console.log("http before");
}
}).then(function(res){
this.msg = res.data;
})
}
})

4.全局拦截器 interceptors, 假如页面中有10个请求都有loading, 不可能10个请求中都写一个, 全局拦截器统一处理

new Vue({
mounted: function(){
// 全局请求拦截
Vue.http.interceptors.push(function(request, next){
// 请求前
console.log("request init."); // 请求后
next(function(response){
console.log("request complete.");
return response;
})
})
},
http:{
// 配置全局地址
root: "http://taoalan.com/" // 公共地址
}
})