当前位置:首页 > VUE

vue实现CRUD

2026-03-27 22:03:44VUE

Vue 实现 CRUD 功能

项目初始化

创建一个 Vue 项目,确保已安装 Vue CLI 或使用 Vite 进行初始化。安装必要的依赖,如 axios 用于 HTTP 请求。

npm create vue@latest my-crud-app
cd my-crud-app
npm install axios

后端 API 准备

假设后端 API 提供以下端点:

  • GET /api/items:获取所有数据
  • POST /api/items:创建新数据
  • PUT /api/items/:id:更新数据
  • DELETE /api/items/:id:删除数据

组件结构

创建主组件 ItemList.vue,包含表格展示数据和操作按钮。

数据获取与展示

使用 axios 获取数据并在表格中渲染。

vue实现CRUD

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</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>
            <button @click="editItem(item)">Edit</button>
            <button @click="deleteItem(item.id)">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  mounted() {
    this.fetchItems();
  },
  methods: {
    fetchItems() {
      axios.get('/api/items')
        .then(response => {
          this.items = response.data;
        })
        .catch(error => {
          console.error('Error fetching items:', error);
        });
    }
  }
};
</script>

创建数据

添加表单和提交逻辑。

<template>
  <div>
    <form @submit.prevent="addItem">
      <input v-model="newItem.name" placeholder="Item name" required>
      <button type="submit">Add</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newItem: { name: '' }
    };
  },
  methods: {
    addItem() {
      axios.post('/api/items', this.newItem)
        .then(response => {
          this.items.push(response.data);
          this.newItem.name = '';
        })
        .catch(error => {
          console.error('Error adding item:', error);
        });
    }
  }
};
</script>

更新数据

添加编辑逻辑和模态框。

vue实现CRUD

<template>
  <div>
    <dialog v-if="editingItem" open>
      <form @submit.prevent="updateItem">
        <input v-model="editingItem.name" required>
        <button type="submit">Save</button>
        <button type="button" @click="editingItem = null">Cancel</button>
      </form>
    </dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      editingItem: null
    };
  },
  methods: {
    editItem(item) {
      this.editingItem = { ...item };
    },
    updateItem() {
      axios.put(`/api/items/${this.editingItem.id}`, this.editingItem)
        .then(response => {
          const index = this.items.findIndex(i => i.id === response.data.id);
          this.items.splice(index, 1, response.data);
          this.editingItem = null;
        })
        .catch(error => {
          console.error('Error updating item:', error);
        });
    }
  }
};
</script>

删除数据

实现删除功能。

<script>
export default {
  methods: {
    deleteItem(id) {
      if (confirm('Are you sure?')) {
        axios.delete(`/api/items/${id}`)
          .then(() => {
            this.items = this.items.filter(item => item.id !== id);
          })
          .catch(error => {
            console.error('Error deleting item:', error);
          });
      }
    }
  }
};
</script>

完整组件整合

将所有功能整合到 ItemList.vue 中,确保数据和方法协同工作。

样式优化

添加基础样式提升用户体验。

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
}
</style>

注意事项

  • 使用 v-model 进行表单数据双向绑定。
  • 错误处理通过 catch 捕获并反馈给用户。
  • 编辑时使用对象副本避免直接修改原数据。

通过以上步骤,Vue 实现的 CRUD 功能可以完成数据的展示、创建、更新和删除操作。

标签: vueCRUD
分享给朋友:

相关文章

vue实现选择本地文件

vue实现选择本地文件

实现文件选择功能 在Vue中实现本地文件选择可以通过HTML原生的<input type="file">元素实现。创建一个基本的文件选择组件: <template> &l…

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Vue 中实现 Autocomplete(自动完成)功能可以通过自定义组件或使用现有库完成。以下是几种常见方法: 方法一:使用 Vue 原生实现 创建…

vue评分实现

vue评分实现

Vue 评分组件实现方法 使用第三方库(如 Element UI) 安装 Element UI: npm install element-ui 引入并注册组件: import Vue from '…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…

vue 实现流程

vue 实现流程

Vue 实现流程 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是 Vue 实现的基本流程: 安装 Vue.js 通过 CDN 引入或使用 npm/yarn 安装:…