运行效果如下:
详细代码:
自行添加vue.min.js文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<fieldset>
<legend>
创建新员工
</legend>
<div>
<label for="name">姓名:</label>
<input type="text" id="name" v-model="newPerson.name">
</div>
<div>
<label for="age">年龄:</label>
<input type="number" id="age" v-model="newPerson.age">
</div>
<div>
<label for="sex">性别:</label>
<select id="sex" v-model="newPerson.sex">
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<div>
<button @click="createPerson">添加</button>
</div>
</fieldset>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<tr v-for="(person,index) in people" :key="index">
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
<td>{{ person.sex }}</td>
<td><button @click="deletePerson(index)">删除</button></td>
</tr>
</tbody>
</table>
</div>
<script src="./js/vue.min.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
newPerson: {
name: "",
age: 0,
sex: "男"
},
people: [
{ name: "张三", age: 30, sex: "男" },
{ name: "李四", age: 30, sex: "男" },
{ name: "王五", age: 30, sex: "男" },
{ name: "赵六", age: 30, sex: "男" }
]
},
methods: {
createPerson: function () {
this.people.push(this.newPerson);
// 添加完newPerson对象后,重置newPerson对象
this.newPerson = {
name: "",
age: 0,
sex: "男"
}
},
deletePerson: function (index) {
if (confirm("删除当前员工信息吗?")) {
this.people.splice(index, 1);
}
}
}
});
</script>
</body>
</html>