vue.js的增删改查
时间: 2023-12-26 17:05:18 浏览: 91
以下是使用Vue.js实现增删改查的示例代码:
1. HTML模板
```html
<div id="app">
<h2>学生列表</h2>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(student, index) in students" :key="student.id">
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>
<button @click="editStudent(index)">编辑</button>
<button @click="deleteStudent(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<h2>添加/编辑学生</h2>
<form @submit.prevent="saveStudent">
<label>姓名:</label>
<input type="text" v-model="currentStudent.name" required>
<br>
<label>年龄:</label>
<input type="number" v-model="currentStudent.age" required>
<br>
<button type="submit">{{ editingIndex === null ? '添加' : '保存' }}</button>
<button type="button" @click="cancelEdit" v-show="editingIndex !== null">取消</button>
</form>
</div>
```
2. Vue实例
```javascript
new Vue({
el: '#app',
data: {
students: [
{ id: 1, name: '张三', age: 18 },
{ id: 2, name: '李四', age: 20 },
{ id: 3, name: '王五', age: 22 }
],
currentStudent: { name: '', age: '' },
editingIndex: null
},
methods: {
saveStudent() {
if (this.editingIndex === null) {
// 添加学生
const newStudent = {
id: this.students.length + 1,
name: this.currentStudent.name,
age: this.currentStudent.age
};
this.students.push(newStudent);
} else {
// 编辑学生
const student = this.students[this.editingIndex];
student.name = this.currentStudent.name;
student.age = this.currentStudent.age;
}
this.currentStudent = { name: '', age: '' };
this.editingIndex = null;
},
editStudent(index) {
// 编辑学生
const student = this.students[index];
this.currentStudent = { name: student.name, age: student.age };
this.editingIndex = index;
},
deleteStudent(index) {
// 删除学生
this.students.splice(index, 1);
},
cancelEdit() {
// 取消编辑
this.currentStudent = { name: '', age: '' };
this.editingIndex = null;
}
}
});
```
在这个示例中,我们使用了Vue.js的模板语法和事件绑定来实现增删改查功能。我们使用了一个数组来存储学生信息,使用v-for指令来循环渲染学生列表。当用户点击“编辑”按钮时,我们将当前学生的信息填充到表单中,当用户点击“保存”按钮时,我们将表单中的信息保存到数组中。当用户点击“删除”按钮时,我们从数组中删除对应的学生信息。
阅读全文
相关推荐















