Vue.js本身沒有提供與服務(wù)端通信的借口,但是通過插件的形式實現(xiàn)了基于Ajax、Jsonp等技術(shù)的服務(wù)端通信。
ps:說明下,從vue2.x開始尤大大推薦使用axios進(jìn)行數(shù)據(jù)交互,關(guān)于axios后續(xù)將繼續(xù)和大家一起學(xué)習(xí)。
今天我們就一起學(xué)習(xí)一下vue-resource。
一、安裝
npm install vue-resource --save
//然后在main.js(入口文件)中引入并注冊
import Vue from 'vue';
import VueResource from 'vue-resource'
Vue.use(VueResource)
二、參數(shù)配置
vue-resource將請求配置分為全局配置、組件實例配置和調(diào)用配置這三部分。并且這三部分的優(yōu)先級依次增高。
1. 全局配置
使用全局配置設(shè)置默認(rèn)值。
Vue.http.options.root = '/root';
2.組件實例配置
在組件實例化的配置參數(shù)http選項中進(jìn)行配置。
new Vue({
http:{
root: './root',
headers{
Authorization: 'Basic datura'
}
}
})
3.方法調(diào)用時配置
new Vue({
methods:{
getData(){
this.$http.get({
url: '/api',
headers: {
Authorization: 'Basic datura'
}
}).then(function(res){
//請求成功的回調(diào)
},function(err){
//請求失敗的回調(diào)
})
}
}
})
三、具體調(diào)用(請求數(shù)據(jù))
1.方式一(底層式)
new Vue({
methods:{
getData(){
//POST請求,帶參數(shù)
this.$http({
url: '/api',
method: 'POST',
data:{
'username': 'datura_lj',
'password': 123456
},
headers: {
'Content-Type': 'x-wwww-form-urlencoded'
}
}).then(function(res){
//請求成功的回調(diào)
},function(err){
//請求失敗的回調(diào)
})
}
}
})
2.方式二(便捷式)
不同于底層式方法,便捷式方法是其實是對底層方法進(jìn)行了封裝,它提供了7種請求API:
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
參數(shù)說明:
| 參數(shù) | 數(shù)據(jù)類型 | 說明 |
|---|---|---|
| url | string | 請求數(shù)據(jù)的地址 |
| body | Obj, FormData, string | request body |
| headers | Obj | request header |
| params | Object | 請求的URL參數(shù)對象 |
| method | string | 請求的HTTP方法,例如:'GET', 'POST'或其他 |
| timeout | number | 單位為毫秒請求超時時間 (0 表示無超時時間) |
| before | function(request) | 請求發(fā)送前的處理函數(shù),類似于jQuery的beforeSend函數(shù) |
| progress | function(event) | ProgressEvent回調(diào)處理函數(shù) |
| credentials | boolean | 表示跨域請求時是否需要使用憑證 |
| emulateHTTP | boolean | 發(fā)送PUT, PATCH, DELETE請求時以HTTP POST的方式發(fā)送,并設(shè)置請求頭的X-HTTP-Method-Override |
| emulateJSON | boolean | 將request body以application/x-www-form-urlencoded content type發(fā)送 |
四、實戰(zhàn)代碼
// 基于全局Vue對象使用http
Vue.http.get('/api', [options]).then(successCallback, errorCallback);
Vue.http.post('/api', [body], [options]).then(successCallback, errorCallback);
// 在一個Vue實例內(nèi)使用$http
this.$http.get('/api', [options]).then(successCallback, errorCallback);
this.$http.post('/api', [body], [options]).then(successCallback, errorCallback);
methods:{
get1:function(){
//發(fā)送get請求
this.$http.get('/api').then(function(res){
//請求成功函數(shù)
},function(){
//請求失敗函數(shù)
});
},
get2:function(){
//發(fā)送get請求
this.$http.get('get.do',
{
a:1,
b:2
}
).then(function(res){
//請求成功函數(shù)
},function(){
//請求失敗函數(shù)
});
},
post:function(){
//發(fā)送post請求
this.$http.post('post.do',
{
a:1,
b:2
}
).then(function(res){
//請求成功函數(shù)
},function(){
//請求失敗函數(shù)
});
},
put:function(){
this.$http.put('put.do',{
"id": 111,
"hascollect": 1
}).then(function(res){
//請求成功函數(shù)
}
},function(err){
//請求失敗函數(shù)
});
}
}