Vuejs发送Ajax请求
一、概况
①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发送跨域请求