编程 使用 Vue3 和 Axios 实现 CRUD 操作

2024-11-19 01:57:50 +0800 CST views 656

使用 Vue3 和 Axios 实现 CRUD 操作

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

准备工作

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

npm install vue@next axios

接下来,我们会使用一个简单的 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

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

npm install axios

项目结构

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

vue-crud-example/
├── public/
├── src/
│   ├── components/
│   │   └── CrudComponent.vue
│   ├── App.vue
│   ├── main.js
└── package.json

我们将在 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">
          <h3>{{ 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 response = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost.value);
        posts.value.push(response.data);
        newPost.value = { title: '', body: '' };
      } catch (error) {
        console.error("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(fetchPosts);

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

<style>
.crud-container {
  max-width: 600px;
  margin: 0 auto;
}
</style>

代码分析

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

  2. 响应式数据

    • posts:存储从 API 获取的所有博客文章。
    • newPost:用于创建新文章的数据模型。
    • isEditing:标志,表明当前是否在编辑状态。
    • currentPost:存储当前编辑的文章信息。
  3. API 请求

    • fetchPosts:在组件挂载时执行,从 API 获取所有文章。
    • createPost:向 API 发送新文章创建请求。
    • editPost:将选中的文章数据填入编辑表单。
    • updatePost:更新选中的文章。
    • deletePost:删除选中的文章。
  4. 样式:我们为组件添加了一些基本样式,使其更可读。

运行项目

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

npm run serve

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

总结

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

复制全文 生成海报 前端开发 JavaScript框架 Web开发

推荐文章

Go 中的单例模式
2024-11-17 21:23:29 +0800 CST
imap_open绕过exec禁用的脚本
2024-11-17 05:01:58 +0800 CST
浅谈CSRF攻击
2024-11-18 09:45:14 +0800 CST
批量导入scv数据库
2024-11-17 05:07:51 +0800 CST
HTML5的 input:file上传类型控制
2024-11-19 07:29:28 +0800 CST
Vue3 中提供了哪些新的指令
2024-11-19 01:48:20 +0800 CST
Vue3中的v-for指令有什么新特性?
2024-11-18 12:34:09 +0800 CST
CSS Grid 和 Flexbox 的主要区别
2024-11-18 23:09:50 +0800 CST
使用 Nginx 获取客户端真实 IP
2024-11-18 14:51:58 +0800 CST
维护网站维护费一年多少钱?
2024-11-19 08:05:52 +0800 CST
介绍25个常用的正则表达式
2024-11-18 12:43:00 +0800 CST
js生成器函数
2024-11-18 15:21:08 +0800 CST
如何优化网页的 SEO 架构
2024-11-18 14:32:08 +0800 CST
介绍 Vue 3 中的新的 `emits` 选项
2024-11-17 04:45:50 +0800 CST
乐观锁和悲观锁,如何区分?
2024-11-19 09:36:53 +0800 CST
Vue3 组件间通信的多种方式
2024-11-19 02:57:47 +0800 CST
Vue 3 是如何实现更好的性能的?
2024-11-19 09:06:25 +0800 CST
用 Rust 构建一个 WebSocket 服务器
2024-11-19 10:08:22 +0800 CST
程序员茄子在线接单