使用使用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 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();