VUE的使用之前只是看了数据绑定、筛选这些基本的功能,没有深入接触。接下来的一个项目会用到VUE来开发,所以又简单看看,热热身~
使用http请求需要用到vue-resource 【 https://github.com/vuejs/vue-resource 】
<script src="plugin/vue/vue.js"></script>
<script src="plugin/vue-resource/dist/vue-resource.js"></script>
写的一个非常简单的数据返回:
<?php
header('Content-type:text/json');
$str = '[{"id":"1","name":"penghui1","age":"20","phone":"15839922830"},
{"id":"2","name":"penghui2","age":"21","phone":"15839922830"},
{"id":"3","name":"penghui3","age":"22","phone":"15839922830"},
{"id":"4","name":"penghui4","age":"23","phone":"15839922830"}]';
echo $str;
?>
返回结果如下:
前戏说完,步入正题,先贴一下效果:
当点击复原按钮进行请求数据 (绑定了get方法):
-------------------------分割线-------------------------
贴代码:
<body>
<div id="app" class="container">
<button class="btn btn-primary" v-on:click="get">复原</button>
<table class="table table-condensed table-hover table-bordered">
<tr class="success">
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>手机号</th>
<th>操作</th>
</tr>
<tbody>
<tr v-for="(user,index) in users">
<td>{{index}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.phone}}</td>
<td>
<div class="btn-group">
<button class="btn btn-primary" v-on:click="edit(user,index)">编辑</button>
<button class="btn btn-danger" v-on:click="deleted(index)">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script src="plugin/vue/vue.js"></script>
<script src="plugin/vue-resource/dist/vue-resource.js"></script>
<script>
new Vue({
el: "#app",
data: {
api:'http://localhost:87/api/student.php',
users: [],
},
methods: {
get: function() {
this.$http.get(this.api,{emulateJSON:true})
.then( (response)=>{
console.log(response.data);
this.users = response.body;
})
.catch(function(response) {
console.log(response);
})
}
},
});
</script>
</body>
get请求之前做过移动端开发,所以这次只是简单使用了一下get方式请求.
在获取到数据时要赋值给模型(this.users),在view上已经进行了数据模型的绑定,所以当this.users更新了数据值之后,页面就加载出来数据了。在http请求时会有很多参数,具体可以参考:
http://www.doc00.com/doc/1001004eg 比较详细
记:还有一些其他的功能操作就不往上写了,实现了添加、删除和编辑功能,代码却比较乱。就先记录一下网络请求和加载吧