03-Vue中的Ajax请求
qgyh 2020-11-04 11:41:54 2020-11-04 109 0
vue-resource的介绍
vue-resource
是Vue高度集成的第三方包。
官网链接:
vue-resource 依赖于 Vue。所以,我们要按照先后顺序,导入vue.js和vue-resource.js文件。
解释:
vue.js
文件向Windows对象暴露了Vue
这个关键词;vue-resource.js
向Vue身上挂载了this.$http
这个属性。于是,我们可以直接写this.$http.get
或者this.$http.post
或者this.$http.jsonp
来调用。
vue-resource 发送Ajax请求
常见的数据请求类型包括:get、post、jsonp。下面我们分别讲一讲。
get 请求
格式举例:
this.$http.get(url) .then(function (result) { // 当发起get请求之后,通过 .then 来设置成功的回调函数 console.log(result.body); // response.body就是服务器返回的成功的数据 var result = result.body; }, function (err) { //err是异常数据 });
获取到的response.body
就是要获取的数据,但直接打印出来是 object,所以要记得转成string。
举例:获取数据
现规定,获取品牌数据的 api 接口说明如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> #app { width: 800px; margin: 20px auto; } #tb { width: 800px; border-collapse: collapse; margin: 20px auto; } #tb th { background-color: #0094ff; color: white; font-size: 16px; padding: 5px; text-align: center; border: 1px solid black; } #tb td { padding: 5px; text-align: center; border: 1px solid black; } </style> <script src="../vue.js"></script> <script src="../vue-resource121.js"></script></head><body> <div id="app"> <input type="text" v-model="id"> <input type="text" v-model="pname"> <button>添加数据</button> <table id="tb"> <tr> <th>编号</th> <th>名称</th> <th>创建时间</th> <th>操作</th> </tr> <tr v-for="item in list"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.ctime}}</td> <td> <a href="javascript:void(0)">删除</a> </td> </tr> </table> </div></body><script> new Vue({ el :'#app', data:{ list:[] }, // Vue对象实例创建成功以后就会自动调用这个方法 created:function(){ this.getlist(); }, methods:{ getlist:function(){ // 请求服务器的api获取到品牌的数据列表 this.$http.get('http://vueapi.ittun.com/api/getprodlist') .then(function(response){ // 1、处理服务器异常信息提示 if(response.body.status != 0){ alert(response.body.message); return; } // 2、处理正常的数据逻辑 this.list = response.body.message; //直接将数据放到list数组当中,页面就会自动显示 console.log(this.list); }); } } });</script></html>
上方代码中,我们用到了生命周期函数created
,意思是:程序一加载,就马上在created
这个函数里执行getlist()
方法。
运