使用 Vue3 和 Axios 实现 CRUD 操作

在当今的前端开发中,Vue.js 作为一款流行的 JavaScript 框架,正在被越来越多的开发者所青睐。尤其是 Vue 3 引入了 Composition API 和更优雅的响应式处理,使得模板编写和状态管理变得更加直观。在这篇博客中,我将带领大家通过一个简单的示例,使用 Vue3 和 Axios 实现基础的 CRUD(创建、读取、更新、删除)操作。

准备工作

在开始之前,我们需要确保已经在项目中安装了 Vue3 和 Axios。如果您的项目还没有这些库,可以通过以下命令安装它们:

npm install vue@next axios
  • 1.

接下来,我们会使用一个简单的 JSON API 作为源。为了方便演示,我们将使用  JSONPlaceholder 这样一个提供虚拟 REST API 的网站。

创建 Vue 3 项目

如果你还没有创建 Vue 3 项目,可以通过 Vue CLI 迅速启动一个项目:

npm install -g @vue/cli
vue create vue-crud-example
cd vue-crud-example
  • 1.
  • 2.
  • 3.

在项目的根目录下,确保安装了 Axios:

npm install axios
  • 1.

项目结构

我们的项目结构可能如下所示:

vue-crud-example/
├── public/
├── src/
│   ├── components/
│   │   └── CrudComponent.vue
│   ├── App.vue
│   ├── main.js
└── package.json
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

我们将在 components 文件夹中创建一个新的组件 CrudComponent.vue,并在其中实现我们的 CRUD 功能。

实现 CRUD 操作

现在,让我们开始编写 CrudComponent.vue 文件:

<template>
  <div class="crud-container">
    <h1>Vue 3 CRUD Example</h1>
    
    <form @submit.prevent="createPost">
      <input v-model="newPost.title" placeholder="Title" required />
      <textarea v-model="newPost.body" placeholder="Body" required></textarea>
      <button type="submit">Create Post</button>
    </form>

    <div v-if="posts.length">
      <h2>Posts</h2>
      <ul>
        <li v-for="post in posts" :key="post.id">
          <3>{{ post.title }}</h3>
          <p>{{ post.body }}</p>
          <button @click="editPost(post)">Edit</button>
          <button @click="deletePost(post.id)">Delete</button>
        </li>
      </ul>
    </div>

    <div v-if="isEditing">
      <h2>Edit Post</h2>
      <form @submit.prevent="updatePost">
        <input v-model="currentPost.title" placeholder="Title" required />
        <textarea v-model="currentPost.body" placeholder="Body" required></textarea>
        <button type="submit">Update Post</button>
        <button @click="cancelEdit">Cancel</button>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  setup() {
    const posts = ref([]);
    const newPost = ref({ title: '', body: '' });
    const isEditing = ref(false);
    const currentPost = ref({ id: null, title: '', body: '' });

    const fetchPosts = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        posts.value = response.data;
      } catch (error) {
        console.error("Error fetching posts:", error);
      }
    };

    const createPost = async () => {
      try {
        const = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost.value);
        posts.value.push(response.data);
        newPost.value { title: '', body: '' };
      } catch (error)        console.error(" creating post:", error);
      }
    };

    const editPost = (post) => {
      isEditing.value = true;
      currentPost.value = { ...post };
    };

    const updatePost = async () => {
      try {
        await axios.put(`https://jsonplaceholder.typicode.com/posts/${currentPost.value.id}`, currentPost.value);
        const index = posts.value.findIndex(post => post.id === currentPost.value.id);
        posts.value[index] = currentPost.value;
        cancelEdit();
      } catch (error) {
        console.error("Error updating post:", error);
      }
    };

    const deletePost async (id) => {
      try {
        await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
        posts.value = posts.value.filter(post => post.id !== id);
      } catch (error) {
        console.error("Error deleting post:", error);
      }
    };

    const cancelEdit = () => {
      isEditing.value = false;
      currentPost.value = { id: null, title: '', body: '' };
    };

    onMounted(fetch);

    return {
      posts,
      newPost,
      isEditing,
      currentPost,
      fetchPosts,
      createPost,
      editPost,
      updatePost,
      deletePost,
      cancelEdit,
    };
  },
};
</script>

<style>
ud-container {
  max-width: 600px;
  margin: 0 auto;
}
</style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
代码分析

. 模板部分: 我们定义了一个简单的表单,用户可以输入新的博文标题和内容。通过 v-for 指令渲染博客列表,并添加编辑和删除按钮。

  1. 响应式数据
  • posts:存储从 API 获取的所有博客文章。
  • newPost:用于创建新文章的数据模型。
  • isEditing:标志,表明当前是否在编辑状态。
  • currentPost:存储当前编辑的文章信息。
  1. API 请求
  • fetchPosts:在组件挂载时执行,从 API 获取所有文章。
  • createPost:向 API 发送新文章创建请求。
  • editPost:将选中的文章数据填入编辑表单。
  • updatePost:更新选中的文章。
  • deletePost:删除选中的文章。
  1. 样式:我们为组件添加了一些基本样式,使其更可读。

运行项目

完成后,我们只需在命令行中运行以下命令,启动开发服务器:

npm run serve
  • 1.

打开浏览器访问 http://localhost:8080,你将能够看到之前写的 CRUD 示例。您现在可以创建新的帖子,查看帖子,更新或删除您不想要的帖子。

总结

在当前的前端开发中,Vue3 和 Axios 无疑是构建高效应用的理想选择。通过本教程所示的简单步骤,您可以快速掌握如何利用这两个工具实现 CRUD 操作。


 最后问候亲爱的朋友们,并诚挚地邀请你们阅读我的全新著作。 书籍简介

使用Vue3和Axios实现CRUD操作_API