一.用vue-resource实现页面数据跟后台的交互。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-resource-1.3.4.js"></script>
<script>Vue.config.productionTip = false</script>
<link rel="stylesheet" href="./lib/bootstrap-3.3.7.css" />
</head>
<body>
<!-- 控制区域 -->
<div class="container">
<!-- 添加功能区域 -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加品牌</h3>
</div>
<div class="panel-body form-inline">
<label>
Name:
<input type="text" v-model="name" class="form-control" />
</label>
<input
type="button"
value="添加"
@click="add"
class="btn btn-primary"
/>
</div>
</div>
<!-- 显示请求数据和删除功能区域 -->
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<!-- prevent是取消<a>本身的默认链接事件,从而只执行click事件 -->
<td><a href="" @click.prevent="del(item.id)">删除</a></td>
</tr>
</tbody>
</table>
</div>
<!-- 实例化 -->
<script>
var vue = new Vue({
el: ".container",
data: {
name: "",
list: [
{ id: 1, name: "五菱" },
{ id: 2, name: "宝马" }
]
},
created() {
this.getList();
},
methods: {
//添加用户
add() {
/**
*第一个参数是url
*第二个参数是要提交给服务器的数据,要以对象形式提交给服务器。
*第三个是配置对象,要以哪种格式提交数据个服务器。{emulateJson:true},以普通表单格式将数据提交给页面。
*/
this.$http.post("http://jsonplaceholder.typicode.com/users",{name:this.name},{emulateJson:true}).then(result =>{
//此网址返回的是添加的数据信息
console.log(result.body);
//添加成功后刷新数据
this.getList();
alert("post数据成功!")
})
},
//获得所有用户信息
getList() {
this.$http
.get("http://jsonplaceholder.typicode.com/users")
.then(result => {
//result是个对象,数据都放默认放在body属性里面,所以直接 result.数据的属性 是拿不到指定数据的。
var result = result.body;
this.list = result;
alert("get数据成功了")
});
},
//删除用户
del(id){
this.$http.get("http://jsonplaceholder.typicode.com/users?"+id).then(result =>{
//此网址返回的是删除的数据信息
console.log(result.body);
//添加成功后刷新数据
this.getList();
alert("删除数据成功!")
})
}
}
});
</script>
</body>
</html>