<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.email }}</td>
<td>
<button @click="editItem(item.id)">Edit</button>
<button @click="deleteItem(item.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<form @submit.prevent="addItem" v-if="showForm">
<input type="text" v-model="formData.name" placeholder="Name" required />
<input type="email" v-model="formData.email" placeholder="Email" required />
<button type="submit">Add</button>
</form>
<button @click="toggleForm">Toggle Form</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
interface Item {
id: number;
name: string;
email: string;
}
export default defineComponent({
name: 'TableComponent',
data() {
return {
items: [] as Item[],
formData: {
name: '',
email: '',
},
showForm: false,
};
},
methods: {
async fetchItems() {
// 调用后端接口获取数据
// 假设接口返回的数据格式为 { data: Item[] }
const response = await fetch('/api/items');
const data = await response.json();
this.items = data.data;
},
async addItem() {
// 调用后端接口添加数据
// 假设接口返回的数据格式为 { data: Item }
const response = await fetch('/api/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.formData),
});
const data = await response.json();
this.items.push(data.data);
this.formData.name = '';
this.formData.email = '';
},
async editItem(itemId: number) {
// 调用后端接口编辑数据
// 假设接口返回的数据格式为 { data: Item }
const response = await fetch(`/api/items/${itemId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.formData),
});
const data = await response.json();
const index = this.items.findIndex((item) => item.id === itemId);
if (index !== -1) {
this.items[index] = data.data;
}
this.formData.name = '';
this.formData.email = '';
},
async deleteItem(itemId: number) {
// 调用后端接口删除数据
await fetch(`/api/items/${itemId}`, {
method: 'DELETE',
});
this.items = this.items.filter((item) => item.id !== itemId);
},
toggleForm() {
this.showForm = !this.showForm;
},
},
mounted() {
this.fetchItems();
},
});
</script>
TableComponent
组件实现了表格的增删改查功能。它使用items
数组来存储从后端接口获取的数据,使用formData
对象来存储表单数据。fetchItems
方法调用后端接口获取数据,并将返回的数据赋值给items
数组。addItem
方法调用后端接口添加数据,并将返回的数据添加到items
数组中。editItem
方法调用后端接口编辑数据,并更新items
数组中对应的数据。deleteItem
方法调用后端接口删除数据,并从items
数组中移除对应的数据。
在模板中,使用v-for
指令遍历items
数组,展示表格中的每一行数据。每一行数据都包含一个"Edit"按钮和一个"Delete"按钮,点击这些按钮会调用相应的方法来编辑或删除数据。表格下方有一个"Toggle Form"按钮,点击该按钮可以切换显示/隐藏添加数据的表单。