基本語法
必須引入一個庫:vue-resource github地址
// 基于全局Vue對象使用http Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); // 在一個Vue實例內使用$http this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
vue-resource的請求API是按照REST風格設計的,它提供了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])
Options
Parameter | Type | Description |
---|---|---|
url | string | 請求的UR |
body | Object, FormData, string | request body |
headers | Object | request header |
params | Object | 請求的URL參數對象 |
method | string | 請求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 |
timeout | number | 單位為毫秒的請求超時時間 (0 表示無超時時間) |
before | function(request) | 請求發送前的處理函數,類似于jQuery的beforeSend函數 |
progress | function(event) | ProgressEvent回調處理函數 |
credentials | boolean | 表示跨域請求時是否需要使用憑證 |
emulateHTTP | boolean | 發送PUT, PATCH, DELETE請求時以HTTP POST的方式發送,并設置請求頭的X-HTTP-Method-Override |
emulateJSON | boolean | 將request body以application/x-www-form-urlencoded content type發送 |
1. 向文本發出get請求
準備一個1.txt 的文本數據,時面的內容是:welcomet to vue!!!
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <script src="http://unpkg.com/vue/dist/vue.js"></script> <script src="http://files.cnblogs.com/files/zycbloger/vue-resource.min.js"></script> <script type="text/javascript"> window.onload = function(){ var vm = new Vue({ el:'#box', data:{ msg:'Hello World!', }, methods:{ get:function(){ //發送get請求 this.$http.get('1.txt').then(function(res){ alert(res.body); },function(){ alert('請求失敗處理'); //失敗處理 }); } } }); } </script> </head> <body> <div id="box"> <input type="button" @click="get()" value="按鈕"> </div> </body> </html>
上面代碼實現了,點擊按鈕,就發送get請求,成功就會執行彈窗 welcomet to vue!!!
2. 關于向后端請求,并帶參數的寫法
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <script src="http://unpkg.com/vue/dist/vue.js"></script> <script src="http://files.cnblogs.com/files/zycbloger/vue-resource.min.js"></script> <script type="text/javascript"> window.onload = function(){ var vm = new Vue({ el:'#box', data:{ msg:'Hello World!', }, methods:{ get:function(){ //發送get請求 this.$http.get('get.do',{a:1,b:2}).then(function(res){ alert(res.body); },function(){ alert('請求失敗處理'); //失敗處理 }); }, post:function(){ //發送post請求 this.$http.post('post.do',{a:1,b:2}).then(function(res){ alert(res.body); },function(){ alert('請求失敗處理'); //失敗處理 }); } } }); } </script> </head> <body> <div id="box"> <input type="button" @click="get()" value="按鈕get"> <input type="button" @click="post()" value="按鈕post"> </div> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。