使用Vue调取接口,并渲染数据的示例代码

刚接触vue.js框架的时候,很伤脑筋。今天整理一下post/get两种方式,简单的调取数据库数据,并进行渲染,希望帮助大家!

首先,在HTML页面引入:

//引入vue.js文件 <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> 引入vue-resource.min.js文件,就可以引入接口方法了 <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

然后,在body中书写div:

//id在下面js中进行引用 <div> <table cellpadding="0" cellspacing="0"> <tr> <td>序号</td> <td>姓名</td> <td>头像</td> </tr> //v-for 循环数据表中的数据 <tr v-for="v in msg"> <td>{{v.id}}</td> <td>{{v.username}}</td> <td>{{v.photo}}</td> </tr> </table> </div>

第三,js代码:

<script type = "text/javascript"> window.onload = function(){ //实例化vue类 var vm = new Vue({ //绑定box el:'#box', data:{ //设置msg内容为空,在请求数据前为空的状态 msg:'', }, mounted:function () { //调取本地的get(就在下面) this.get(); }, methods:{ get:function(){ //发送get请求 this.$http.post('http://你的IP/api/方法',{key:"密钥"},{emulateJSON:true}).then(function(res){ //msg等于回调函数返回的res(值) this.msg=res.body.data; //在打印台测试打印,无误后一定要删除 console.log(res); },function(){ console.log('请求失败处理'); }); } } }); } </script>

控制器:

public function index() { // //引入秘钥 $pwd=new ApisModel(); $passwd=$pwd->passwd(); // print_r($passwd);die; //空的数组,等待输入秘钥与存储在model层的秘钥对比 $date=request()->get(); // print_r($date);die; // 对比秘钥是否一致 if($date['key']==$passwd){ $model=new ApisModel(); $data=$model->role_show(); return json(array('data'=>$data,'code'=>1,'message'=>'操作完成')); }else{ $data = ['name'=>'status','message'=>'操作失败']; return json(['data'=>$data,'code'=>2,'message'=>'秘钥不正确']); } }

model:

public function passwd(){ $key='存放在本地的密钥'; return $key; } //简单的测试接口 public function role_show(){ return Db::name('role_power')->select(); }

OK,post方式搞定了,下面是vue使用get方法进行接口调用,渲染数据

简单粗暴,大致一样,就不一一详解了,上代码:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script> </head> <body> <div> <table cellpadding="0" cellspacing="0"> <tr> <td>ROLE_ID</td> <td>POWER_ID</td> <td>创建时间</td> </tr> <tr v-for="v in msg"> <td>{{v.role_id}}</td> <td>{{v.power_id}}</td> <td>{{v.create_time}}</td> </tr> </table> </div> <script type = "text/javascript"> window.onload = function(){ var vm = new Vue({ el:'#box', data:{ msg:'', }, mounted:function () { this.get(); }, methods:{ get:function(){ //发送get请求 this.$http.get("http://ip?key=密钥",{emulateJSON:true}).then(function(res){ console.log(res.body); this.msg=res.body.data; },function(){ console.log('请求失败处理'); }); } } }); } </script> </body> </html>

ok,都测试好了,可以使用,千万别搞错id哦。

以上这篇使用Vue调取接口,并渲染数据的示例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/76b152c9b2b222ead3badbbb3c989221.html