当前位置:首页 > 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 获取数据并在表格中渲染。

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

更新数据

添加编辑逻辑和模态框。

<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 中,确保数据和方法协同工作。

样式优化

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

vue实现CRUD

<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 实现同步的方法 在 Vue 中实现同步操作通常涉及数据绑定、状态管理和异步操作的处理。以下是几种常见的方法: 使用计算属性(Computed Properties) 计算属性基于响应式依赖进…

vue实现全景

vue实现全景

Vue 实现全景效果的方法 使用 Vue 实现全景效果通常需要结合第三方库或框架,以下是几种常见的方法: 使用 Three.js 和 Vue-Three.js Three.js 是一个强大的 3D…

vue实现树

vue实现树

Vue 实现树形结构的方法 使用递归组件实现树形结构 递归组件是Vue中实现树形结构的常见方式。通过组件调用自身,可以轻松构建多层嵌套的树形数据。 <template> <ul…

vue实现注销

vue实现注销

实现用户注销功能 在Vue应用中实现用户注销功能通常涉及清除用户会话、重置应用状态并跳转到登录页面。以下是具体实现方法: 清除用户认证信息 使用Vuex或Pinia管理用户状态时,需在注销时重置存储…

vue多选实现

vue多选实现

Vue 多选实现方法 基础实现(v-model + multiple) 在 Vue 中实现多选可以通过 <select> 元素的 multiple 属性结合 v-model 完成。v-mo…

vue 实现平面

vue 实现平面

Vue 实现平面的方法 在 Vue 中实现平面效果通常涉及 CSS 样式、UI 框架或自定义组件的使用。以下是几种常见方法: 使用 CSS 样式 通过 Vue 的样式绑定或 scoped CSS 为…