vue语法小练习

时间:2023-03-08 21:55:00

实现功能:新增/删除 学生

<html>

  <head>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head> <body>
<div id="app">
<fieldset>
<legend>学生信息新增</legend>
<div>
<span>姓名</span>
<input type="text" v-model="newStudent.name" placeholder="please input your name"></div>
<div>
<span>年龄</span>
<input type="text" v-model="newStudent.age" placeholder="please input your age"></div>
<div>
<span>性别</span>
<select v-model="newStudent.sex">
<option value="男">男</option>
<option value="女">女</option></select>
</div>
<button @click="insert()">添加</button></fieldset>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th></tr>
</thead>
<tbody>
<tr v-for="(st, index) in students">
<td>{{st.name}}</td>
<td>{{st.age}}</td>
<td>{{st.sex}}</td>
<td>
<button @click="del(index)">Delete</button></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<script>new Vue({
el: '#app',
data: {
students: [{
name: '张三',
age: 12,
sex: '男'
},
{
name: '李四',
age: 14,
sex: '女'
},
{
name: '王五',
age: 15,
sex: '男'
},
],
newStudent: {
name: '',
age: 0,
sex: '男'
}
},
methods: {
insert() {
this.students.unshift(this.newStudent)
//重置表单数据
this.newStudent = {
name: '',
age: 0,
sex: '男'
}
},
del(index) {
this.students.shift(index, 1)
}
}
})</script>
</body> </html>