1.表格的增加和删除
题目:
解答:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welcome to vue</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="form">
<div>
<span>
<div style="display: inline-block">ID: </div>
<input v-model="id" type="text">
</span>
<span>
<div style="display: inline-block">姓名: </div>
<input v-model="name" type="text">
</span>
<span>
<div style="display: inline-block">email: </div>
<input v-model="email" type="text">
</span>
<span>
<div style="display: inline-block">性别: </div>
<input v-model="sex" type="text">
</span>
<span>
<button v-on:click="submit" style="display: inline-block">添加</button>
<button v-on:click="reset" style="display: inline-block">重置</button>
</span>
</div>
<table border="1" style="margin: auto;margin-top: 3em">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in items">
<td>{{ item.ID }}</td>
<td>{{ item.Name }}</td>
<td>{{ item.Email }}</td>
<td>{{ item.Sex }}</td>
<td><a href="#" v-on:click="remove(index)">删除</a></td>
</tr>
</tbody>
</table>
</div>
<script>
new Vue({
el:'#form',
data: {
items: [
{ID: '1',Name: '刘一',Email: '123@126.com',Sex: '男'},
{ID: '2',Name: '刘一',Email: '123@126.com',Sex: '男'}
],
id: '',
name: '',
email: '',
sex: ''
},
methods: {
submit() {
let id = this.id;
let name = this.name;
let email = this.email;
let sex = this.sex;
let obj = {
ID: id,
Name: name,
Email: email,
Sex: sex
}
this.items.unshift(obj);
},
remove(index){
this.items.splice(index,1)
},
reset(){
this.id = '';
this.name = '';
this.email = '';
this.sex = '';
}
}
})
</script>
</body>
</html>
知识点:
- v-model双向绑定,v-bind单向绑定,splice删除数组元素,push和unshift添加元素,unshift添加到头部,push添加到尾部
Comments