<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="vue-2.5.13.min.js"></script>
<style>
* {
padding: 0;
margin: 0;
position: relative;
}
/* 实现任意无宽高盒子居中显示 */
#app {
position: absolute;
left: 50%;
top: 100px;
transform: translateX(-50%);
}
.box {
width: 500px;
height: 40px;
background-color: #ccc;
display: inline-block;
text-align: center;
line-height: 40px;
border: 1px solid #aaa;
box-sizing: border-box;
border-bottom: none;
}
.tb {
width: 500px;
text-align: center;
border-collapse: collapse;
border-color: #ccc;
}
</style>
</head>
<body>
<div id="app">
<div class="box">
<label for="id">
ID:
<input type="text" id="id" v-model="id">
</label>
<label for="name">
name:
<input type="text" id="name" v-model="name">
</label>
<input type="button" value="add" @click="addClick">
</div>
<table border="1" cellspacing="0" class="tb">
<tr v-for="item in list">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.ctime}}</td>
<td>
<!-- 绑定的事件是可以传参数的,这里传入需要删除的对象id -->
<a href="javascript:;" @click.prevent="delClick(item.id)">del</a>
</td>
</tr>
</table>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
id: "",
name: "",
list: [{
id: 1,
name: ‘tony‘,
ctime: new Date()
},
{
id: 2,
name: ‘stark‘,
ctime: new Date()
}
]
},
methods: {
addClick() {
// 1.获取表单数据
// 2.组织出一个对象
// 3.将对象添加到data中(不需要重新渲染页面)
let item = {
id: this.id,
name: this.name,
ctime: new Date()
};
if ((this.id != "") && (this.name != "")) {
this.list.push(item);
}
// 4.最后将表单清空
this.id = this.name = "";
},
delClick(id) {
// 1.根据id找到索引(循环查找)
// 2.调用数组的 splice方法删除
this.list.filter((item, index) => {
if (item.id == id) {
this.list.splice(index, 1);
return true;
}
});
}
}
});
</script>
</body>
</html>