Vue实现表格数据的增删改查
在Vue中实现表格数据的增删改查,你可以使用Vue的响应式特性和组件化的方法。以下是一个简单的示例,展示了如何实现这些功能:
<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="editItem(index)">Edit</button>
<button @click="deleteItem(index)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div v-if="editMode">
<input type="text" v-model="editItemId">
<input type="text" v-model="editItemName">
<input type="number" v-model="editItemAge">
<button @click="updateItem">Update</button>
<button @click="cancelEdit">Cancel</button>
</div>
<div v-else>
<input type="text" v-model="newItemName">
<input type="number" v-model="newItemAge">
<button @click="addItem">Add</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'John Doe', age: 30 },
{ id: 2, name: 'Jane Smith', age: 25 },
// ... more items
],
newItemName: '',
newItemAge: null,
editMode: false,
editItemId: null,
editItemName: '',
editItemAge: null,
};
},
methods: {
addItem() {
const newItem = {
id: this.items.length + 1,
name: this.newItemName,
age: this.newItemAge
};
this.items.push(newItem);
this.newItemName = '';
this.newItemAge = null;
},
editItem(index) {
this.editMode = true;
this.editItemId = this.items[index].id;
this.editItemName = this.items[index].name;
this.editItemAge = this.items[index].age;
},
updateItem() {
const index = this.items.findIndex(item => item.id === this.editItemId);
if (index !== -1) {
this.items.splice(index, 1, {
id: this.editItemId,
name: this.editItemName,
age: this.editItemAge
});
评论已关闭