vue假的增删改查实现
时间: 2024-05-25 20:06:39 浏览: 12
以下是一个简单的Vue假的增删改查实现的例子:
```html
<template>
<div>
<h2>用户列表</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in userList" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>
<button @click="editUser(user)">编辑</button>
<button @click="deleteUser(user)">删除</button>
</td>
</tr>
</tbody>
</table>
<h2>编辑用户</h2>
<form @submit.prevent="saveUser">
<label for="name">姓名:</label>
<input type="text" id="name" v-model="editUser.name" required>
<br>
<label for="age">年龄:</label>
<input type="number" id="age" v-model="editUser.age" required>
<br>
<button type="submit">保存</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
userList: [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 25 },
{ id: 3, name: '王五', age: 30 }
],
editUser: {
id: null,
name: '',
age: null
}
};
},
methods: {
editUser(user) {
this.editUser.id = user.id;
this.editUser.name = user.name;
this.editUser.age = user.age;
},
deleteUser(user) {
const index = this.userList.findIndex(u => u.id === user.id);
if (index !== -1) {
this.userList.splice(index, 1);
}
},
saveUser() {
if (this.editUser.id) {
const index = this.userList.findIndex(u => u.id === this.editUser.id);
if (index !== -1) {
this.userList[index].name = this.editUser.name;
this.userList[index].age = this.editUser.age;
}
} else {
const newUser = {
id: this.userList.length + 1,
name: this.editUser.name,
age: this.editUser.age
};
this.userList.push(newUser);
}
this.editUser.id = null;
this.editUser.name = '';
this.editUser.age = null;
}
}
};
</script>
```
这个例子展示了一个简单的用户列表,可以进行增删改查操作。用户列表数据存储在Vue组件的data中的userList数组中。通过v-for指令遍历userList数组,渲染出每个用户的信息。点击编辑按钮可以将用户信息填充到编辑表单中,点击保存按钮可以保存编辑后的用户信息。点击删除按钮可以删除对应的用户。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)