方式一步驟:
1、在當前項目中安裝vue-resource
- 命令窗口輸入:npm install vue-resource --save
2、安裝完成后,在main.js中導入
import VueResource from vue-resource //引入
Vue.use(VueResource) //使用
方式二步驟:
1、直接在頁面中,通過script標簽,引入 vue-resource的腳本文件;
2、引入vue.js和vue-resource.js,注意先后順序,先引vue.js。記住所有vue插件都需要在vue.js之后加載。
引用:
1、發送get請求:
getInfo() { // get 方式獲取數據
this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
console.log(res.body);
})
}
//通過.then拿到服務器返回的數據
2、發送post請求:
postInfo() {
var url = 'http://127.0.0.1:8899/api/post';
// post 方法接收三個參數:
// 參數1: 要請求的URL地址
// 參數2: 要發送的數據對象格式
// 參數3: 指定post提交的編碼類型為 application/x-www-form-urlencoded
this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
console.log(res.body);
});
}
//手動發起的post請求,默認沒有表單格式,所以,有的服務器處理不了,通過post方法的第三個參數{ emulateJSON: true }設置提交的內容類型為普通表單數據格式。
3、發送JSONP
請求獲取數據:
jsonpInfo() { // JSONP形式從服務器獲取數據
var url = 'http://127.0.0.1:8899/api/jsonp';
this.$http.jsonp(url).then(res => {
console.log(res.body);
});
}
4、支持的HTTP方法
vue-resource的請求API是按照REST風格設計的,它提供了7種請求API:
- get(url, [options])
- head(url, [options])
- elete(url, [options])
- jsonp(url, [options])
- post(url, [body], [options])
- put(url, [body], [options])
- patch(url, [body], [options])
注意:
-
url,請求地址。可被options對象中url屬性覆蓋。
-
body(可選,字符串或對象),要發送的數據,可被options對象中的body屬性覆蓋。
-
options 請求選項對象
參數 類型 描述 url string 請求的URL method string 請求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 body Object,FormDatastring request body params Object 請求的URL參數對象 headers Object request header timeout number 單位為毫秒的請求超時時間 (0 表示無超時時間) before function(request) 請求發送前的處理函數,類似於jQuery的beforeSend函數 progress function(event) ProgressEvent回調處理函數 credentials boolean 表示跨域請求時是否需要使用憑證 emulateHTTP boolean 發送PUT, PATCH, DELETE請求時以HTTP emulateJSON boolean 將request body以application/x-www-form-urlencoded content type發送