一、概況
①vuejs中沒有內置任何ajax請求方法
②在vue1.0版本,使用的插件 vue resource 來發送請求,支持promise
③在vue2.0版本,使用社區的一個第三方庫 axios ,也支持promise
④在HTML5時代,瀏覽器增加了一個特殊的異步請求方法 fetch,原生支持promise,由於兼容性問題,一般用於移動端
⑤還有的項目會使用vue和jquery混用,借助jQuery的ajax方法
二、axios庫的使用
①安裝和引入:
- npm直接下載axios組件,下載完畢后axios.js就存放在node_modules\axios\dist中
npm install axios
- 網上直接下載axios.min.js文件,或者使用cdn,通過script src的方式進行文件的引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
②發送get請求
- 基本使用格式:
axios([options]) #這種格式直接將所有數據寫在options里,options其實是個字典
axios.get(url[,options]);
- 傳參方式:通過url傳參,通過params選項傳參
- 案例:
<div id="app"> <button @click='send'>發送Ajax請求</button> <button @click='sendGet'>GET方式發送Ajax請求</button> </div> <script src="node_modules/vue/dist/vue.js"></script> <script src="node_modules/axios/dist/axios.min.js"></script> <script> new Vue({ el:'#app', data:{ user:{name:'eric',age:24}, }, methods:{ send(){ axios({ method:'get', url:'http://www.baidu.com?name=jack&age=30' }).then(function(resp){ console.log(resp.data); }).catch(err=>{ console.log('請求失敗:'+err.status+','+err.statusText); }); }, sendGet(){ axios.get('server.php',{ params:{name:'tom',age:20} }).then(resp=>{ console.log(resp.data) }).catch(resp=>{ console.log('請求失敗:'+err.status+','+err.statusText); }); }, }, }); </script>
③發送post請求(push,delete的非get方式的請求都一樣)
- 基本使用格式
axios.post(url,data,[options]);
- 傳參方式:自己拼接為鍵值對;使用transformRequest,在請求發送前將請求數據進行轉換;如果使用模塊化開發,可以使用qs模塊進行轉換;
- 注意:axios默認發送post數據時,數據格式是Request Payload,並非我們常用的Form Data格式,所以參數必須要以鍵值對形式傳遞,不能以json形式傳參
- 案例:
<div id="app"> <button @click='sendPost'>post方式發送Ajax請求</button> </div> <script src="node_modules/vue/dist/vue.js"></script> <script src="node_modules/axios/dist/axios.min.js"></script> <script> new Vue({ el:'#app', data:{ user:{name:'eric',age:24}, }, methods:{ sendPost(){ axios.post('server.php',this.user,{ transformRequest:[ function(data){ let params=''; for(let index in data){ params+=index+'='+data[index]+'&'; } return params; } ] }).then(resp=>{ console.log(resp.data) }).catch(err=>{ console.log('請求失敗:'+err.status+','+err.statusText); }); }, }, }); </script>
④發送跨域請求:axios本身並不支持發送跨域的請求,沒有提供相應的API,作者也暫沒計划在axios添加支持發送跨域請求,所以只能使用第三方庫,可以使用vue-resource發送跨域請求