12-vue-resource的基本使用
阿新 • • 發佈:2020-12-08
傳送請求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> <!-- 注意:vue-resource 依賴於 Vue,所以先後順序要注意 --> <!-- this.$http.jsonp --> <script src="./lib/vue-resource-1.3.4.js"></script> </head> <body> <div id="app"> <input type="button" value="get請求" @click="getInfo"> <input type="button" value="post請求" @click="postInfo"> <input type="button" value="jsonp請求" @click="jsonpInfo"> </div> <script> // 建立 Vue 例項,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getInfo() { // 發起get請求 // 當發起get請求之後, 通過 .then 來設定成功的回撥函式 this.$http.get('http://vue.studyit.io/api/getlunbo').then(function (result) { // 通過 result.body 拿到伺服器返回的成功的資料 // console.log(result.body) }) }, postInfo() { // 發起 post 請求 application/x-wwww-form-urlencoded // 手動發起的 Post 請求,預設沒有表單格式,所以,有的伺服器處理不了 // 通過 post 方法的第三個引數, { emulateJSON: true } 設定 提交的內容型別 為 普通表單資料格式 this.$http.post('http://vue.studyit.io/api/post', {}, { emulateJSON: true }).then(result => { console.log(result.body) }) }, jsonpInfo() { // 發起JSONP 請求 this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => { console.log(result.body) }) } } }); </script> </body> </html>