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

2020-06-12 20:52:24易采站长站整理

刚接触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 id="box">

<table border="1" 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='存放在本地的密钥';