<!-- BookList.vue -->
<template>
<div>
<h1>My Book List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Published Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="book in books" :key="book.id">
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>{{ book.author }}</td>
<td>{{ book.publishedDate }}</td>
<td>
<button @click="editBook(book)">Edit</button>
<button @click="deleteBook(book)">Delete</button>
</td>
</tr>
</tbody>
</table>
<button @click="addBook">Add Book</button>
</div>
</template>
<script>
export default {
data() {
return {
books: [], // 初始化数据
selectedBook: null, // 选中的书籍对象
showModal: false // 是否显示模态框
};
},
methods: {
// 获取书籍列表
async getBooks() {
const response = await fetch("/api/books");
this.books = await response.json();
},
// 添加书籍
async addBook() {
this.selectedBook = null;
this.showModal = true;
},
// 编辑书籍
async editBook(book) {
this.selectedBook = book;
this.showModal = true;
},
// 保存书籍
async saveBook(book) {
let response;
if (book.id) {
response = await fetch(`/api/books/${book.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(book)
});
} else {
response = await fetch("/api/books", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(book)
});
}
if (response.ok) {
this.showModal = false;
this.getBooks();
}
},
// 删除书籍
async deleteBook(book) {
const response = await fetch(`/api/books/${book.id}`, { method: "DELETE" });
if (response.ok) {
this.getBooks();
}
}
},
mounted() {
this.getBooks();
}
};
</script>
// Book Model
{
id: number,
title: string,
author: string,
publishedDate: Date
}