vuejs增删改查的代码

<!-- 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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值