用vue2语法写一个包含增删改查的表格页面
时间: 2024-06-01 21:12:53 浏览: 56
lib-ui:与iris-gorm-demo对应的前端代码,vue+element写的增删改查页面
好的,我可以为您提供这个问题的答案,以下是一个用Vue2语法编写的包含增删改查操作的表格页面的示例代码:
<template>
<div>
<h1>学生列表</h1>
<table>
<thead>
<tr>
<th>#</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(student, index) in students" :key="student.id">
<td>{{ index + 1 }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.gender }}</td>
<td>
<button @click="editStudent(index)">编辑</button>
<button @click="deleteStudent(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<form v-if="editing !== null" @submit.prevent="saveStudent">
<h2>编辑学生信息</h2>
<div>
<label for="name">姓名:</label>
<input type="text" id="name" v-model="editing.name" />
</div>
<div>
<label for="age">年龄:</label>
<input type="number" id="age" v-model="editing.age" />
</div>
<div>
<label for="gender">性别:</label>
<select id="gender" v-model="editing.gender">
<option value="male">男</option>
<option value="female">女</option>
</select>
</div>
<button type="submit">保存</button>
<button type="button" @click="cancelEdit">取消</button>
</form>
<form v-else @submit.prevent="addStudent">
<h2>添加学生</h2>
<div>
<label for="name">姓名:</label>
<input type="text" id="name" v-model="newStudent.name" />
</div>
<div>
<label for="age">年龄:</label>
<input type="number" id="age" v-model="newStudent.age" />
</div>
<div>
<label for="gender">性别:</label>
<select id="gender" v-model="newStudent.gender">
<option value="male">男</option>
<option value="female">女</option>
</select>
</div>
<button type="submit">添加</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
students: [
{ id: 1, name: '张三', age: 18, gender: 'male' },
{ id: 2, name: '李四', age: 20, gender: 'male' },
{ id: 3, name: '王五', age: 22, gender: 'female' },
],
newStudent: {
name: '',
age: '',
gender: '',
},
editing: null,
};
},
methods: {
addStudent() {
const student = {
id: new Date().getTime(),
...this.newStudent,
};
this.students.push(student);
this.newStudent = { name: '', age: '', gender: '' };
},
editStudent(index) {
this.editing = { ...this.students[index] };
this.students.splice(index, 1);
},
saveStudent() {
this.students.push(this.editing);
this.editing = null;
},
cancelEdit() {
this.students.push(this.editing);
this.editing = null;
},
deleteStudent(index) {
this.students.splice(index, 1);
},
},
};
</script>
希望这个示例代码能够帮到您,如果您有任何其他问题,欢迎随时向我提问。
阅读全文