写一个Vue3脚手架人员信息的添加、删除和修改
时间: 2024-03-08 08:47:19 浏览: 27
好的,下面是一个使用 Vue3 脚手架的人员信息的添加、删除和修改示例:
首先,在 App.vue 文件中定义一个人员信息列表,并通过 v-for 指令遍历展示:
```vue
<template>
<div class="container">
<h1>Person List</h1>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="(person, index) in persons" :key="index">
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td>{{ person.email }}</td>
<td>
<button @click="editPerson(index)">Edit</button>
<button @click="deletePerson(index)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div class="form-container">
<h2>{{ currentAction }}</h2>
<form @submit.prevent="handleSubmit">
<div>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" v-model="person.firstName" required>
</div>
<div>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" v-model="person.lastName" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="person.email" required>
</div>
<button type="submit">{{ currentAction }}</button>
</form>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'App',
setup() {
const persons = ref([
{ firstName: 'John', lastName: 'Doe', email: 'johndoe@example.com' },
{ firstName: 'Jane', lastName: 'Doe', email: 'janedoe@example.com' },
{ firstName: 'Bob', lastName: 'Smith', email: 'bobsmith@example.com' }
]);
const person = ref({ firstName: '', lastName: '', email: '' });
const currentAction = ref('Add Person');
const currentIndex = ref(-1);
const handleSubmit = () => {
if (currentIndex.value === -1) {
// Add new person
persons.value.push(person.value);
} else {
// Update existing person
persons.value[currentIndex.value] = person.value;
currentIndex.value = -1;
}
person.value = { firstName: '', lastName: '', email: '' };
currentAction.value = 'Add Person';
}
const deletePerson = (index) => {
persons.value.splice(index, 1);
}
const editPerson = (index) => {
currentIndex.value = index;
person.value = Object.assign({}, persons.value[index]);
currentAction.value = 'Edit Person';
}
return {
persons,
person,
currentAction,
handleSubmit,
deletePerson,
editPerson
}
}
}
</script>
```
在 setup 函数中,使用 ref 创建一个 persons 变量来存储人员信息列表,再创建一个 person 变量来存储当前编辑的人员信息,以及一个 currentAction 变量来存储当前操作(添加或编辑)。同时,定义 handleSubmit、deletePerson、editPerson 三个方法来处理表单提交、删除和编辑操作。
其中,handleSubmit 方法根据 currentIndex 变量的值来判断是添加新人员信息,还是修改已有的人员信息。如果 currentIndex 的值为 -1,则表示当前是添加新人员信息;否则,表示当前是修改已有的人员信息。
deletePerson 方法接收一个 index 参数,用于删除 persons 列表中的指定人员信息。
editPerson 方法接收一个 index 参数,用于编辑 persons 列表中的指定人员信息。这里使用 Object.assign 方法来复制当前人员信息,以避免直接修改原始对象。
最后,在表单中使用 v-model 指令来双向绑定 person 对象的属性,并在添加和编辑按钮上使用 @click 事件监听器来触发相应的操作。
这样,就实现了一个简单的 Vue3 脚手架人员信息的添加、删除和修改功能。