帮我生成一个vue组件表格,带增删改查的
时间: 2024-03-24 19:12:52 浏览: 67
好的,我可以为您生成一个Vue组件表格,包括增删改查的功能。以下是一个简单的示例:
```
<template>
<div>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="editItem(item)">Edit</button>
<button @click="deleteItem(item)">Delete</button>
</td>
</tr>
</tbody>
</table>
<form v-if="showForm" @submit.prevent="saveChanges">
<input type="text" v-model="currentItem.name">
<input type="number" v-model="currentItem.age">
<button type="submit">{{ currentItem.id ? 'Save' : 'Add' }}</button>
<button type="button" @click="resetForm">Cancel</button>
</form>
<button @click="addItem">Add Item</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{id: 1, name: 'John Doe', age: 25},
{id: 2, name: 'Jane Smith', age: 30},
{id: 3, name: 'Bob Johnson', age: 40},
],
showForm: false,
currentItem: {
id: null,
name: '',
age: null,
},
};
},
methods: {
editItem(item) {
this.currentItem = Object.assign({}, item);
this.showForm = true;
},
deleteItem(item) {
this.items = this.items.filter((i) => i.id !== item.id);
},
resetForm() {
this.currentItem = {id: null, name: '', age: null};
this.showForm = false;
},
saveChanges() {
if (this.currentItem.id) {
this.items = this.items.map((i) =>
i.id === this.currentItem.id ? this.currentItem : i
);
} else {
this.currentItem.id = this.items.length + 1;
this.items.push(this.currentItem);
}
this.resetForm();
},
addItem() {
this.currentItem = {id: null, name: '', age: null};
this.showForm = true;
},
},
};
</script>
```
您可以将此代码复制到您的Vue项目中。这个示例包含一个表格,用于显示项目列表,并允许用户编辑和删除项目。此外,它还包括一个显示表单以添加新项目的按钮,并允许添加和保存项目。
阅读全文