目錄:
- Vue-resource介紹
- 基本用法
- 用vue-resource發送jsonp請求
一、Vue-resource介紹
使用Vue-resource發送跨域請求,安裝vue-resource並引入
cnpm install vue-resource -S
或者自己手動下載vue-resource.min.js
Vue-resouce其實跟axios是一樣的,但是官方建議使用axios,但是大部分公司還在用vue-resouce,因為axios不支持 jsonp跨域請求,但是vue-resource支持的。
我們查看一下 vue-resource的github的官方地址:Github官方地址(這個里面有很詳細的vue-resource的使用方法),也可以在 百度文本框: GitHub vue-resource。
如圖:
二、基本用法
使用this.$http發送請求
this.$http.get(url, [config]) this.$http.head(url, [config]) this.$http.delete(url, [config]) this.$http.jsonp(url, [config]) this.$http.post(url, [body], [config]) this.$http.put(url, [body], [config]) this.$http.patch(url, [body], [config])
詳細使用方法,請查看官網:vue-ressource官方使用文檔
三、用vue-resource發送jsonp請求
2.1、語法
說明:當你引入vue-resource是,則vue實例對象中$http,其實這個$http就是指的是vue-resource
this.$http.jsonp("跨域請求的URL",{ params:{ word:'shuaigaogao', //請求參數 } }).then(resp => { console.log(resp.body.s); //請求成功 }).catch(err => { console.log(err ); //請求失敗 }).then(function() { console.log("不管怎么樣都要執行"); //相當於 finally });
2.2、模擬360搜索關鍵字
說明:這個是通過抓包的方式獲取360搜索接口
<body> <div id="box"> <button @click="sendJsonp">發送jsonp請求</button> </div> <script type="text/javascript" src="../vue.js"></script> <!--引入vue-resource--> <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script> <script> new Vue({ el:"#box", methods:{ sendJsonp(){ this.$http.jsonp("https://sug.so.360.cn/suggest",{ //請求360搜索接口,是通過抓包獲取的 params:{ word:'huawei', } }).then(resp => { //請求成功 console.log(resp.body.s); }) } } }) </script> </body>
輸出結果,如下:
2.3、模擬百度搜索服關鍵字
jsonp: 'cb' => 修改jsonp的參數名稱,把callback改為cb。
<body> <div id="box"> <button @click="sendJsonp">發送jsonp請求</button> </div> <script type="text/javascript" src="../vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script> <script> new Vue({ el:"#box", methods:{ sendJsonp(){ this.$http.jsonp("https://sp0.baidu.com/5b1ZeDe5KgQFm2e88IuM_a",{ params:{ wd:'huawei', }, jsonp: 'cb' //百度使用時jsonp參數名改為cb,所以需要修改 }).then(resp => { console.log(resp); }); } } }) </script> </body>