当前位置:首页 > VUE

vue实现CRUD

2026-01-08 00:44:12VUE

Vue 实现 CRUD 操作

Vue 提供了响应式数据绑定和组件化开发能力,结合后端 API 可以轻松实现 CRUD(增删改查)功能。以下是基于 Vue 3 和 Axios 的完整实现方案。

安装依赖

确保项目中已安装 axios 用于 HTTP 请求:

npm install axios

基础组件结构

创建一个 UserList.vue 组件作为示例:

<template>
  <div>
    <button @click="showAddModal">添加用户</button>
    <table>
      <tr v-for="user in users" :key="user.id">
        <td>{{ user.name }}</td>
        <td>
          <button @click="editUser(user)">编辑</button>
          <button @click="deleteUser(user.id)">删除</button>
        </td>
      </tr>
    </table>

    <!-- 添加/编辑模态框 -->
    <dialog v-if="showModal">
      <input v-model="currentUser.name" placeholder="姓名">
      <button @click="saveUser">保存</button>
      <button @click="closeModal">取消</button>
    </dialog>
  </div>
</template>

数据与状态管理

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

export default {
  setup() {
    const users = ref([])
    const showModal = ref(false)
    const currentUser = ref({ id: null, name: '' })
    const isEditMode = ref(false)

    const fetchUsers = async () => {
      const response = await axios.get('/api/users')
      users.value = response.data
    }

    onMounted(fetchUsers)

    return {
      users,
      showModal,
      currentUser,
      isEditMode,
      fetchUsers
    }
  }
}
</script>

CRUD 方法实现

methods: {
  showAddModal() {
    this.currentUser = { id: null, name: '' }
    this.isEditMode = false
    this.showModal = true
  },

  editUser(user) {
    this.currentUser = { ...user }
    this.isEditMode = true
    this.showModal = true
  },

  async saveUser() {
    if (this.isEditMode) {
      await axios.put(`/api/users/${this.currentUser.id}`, this.currentUser)
    } else {
      await axios.post('/api/users', this.currentUser)
    }
    this.fetchUsers()
    this.closeModal()
  },

  async deleteUser(id) {
    if (confirm('确定删除吗?')) {
      await axios.delete(`/api/users/${id}`)
      this.fetchUsers()
    }
  },

  closeModal() {
    this.showModal = false
  }
}

样式优化

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
tr:nth-child(even) {
  background-color: #f2f2f2;
}
dialog {
  padding: 20px;
  border-radius: 5px;
}
</style>

进阶优化方案

使用 Pinia 进行状态管理

创建 usersStore.js

import { defineStore } from 'pinia'

export const useUsersStore = defineStore('users', {
  state: () => ({
    users: [],
    currentUser: null
  }),
  actions: {
    async fetchUsers() {
      const res = await axios.get('/api/users')
      this.users = res.data
    },
    async saveUser(user) {
      if (user.id) {
        await axios.put(`/api/users/${user.id}`, user)
      } else {
        await axios.post('/api/users', user)
      }
      this.fetchUsers()
    }
  }
})

表单验证

添加 Vuelidate 进行验证:

import { useVuelidate } from '@vuelidate/core'
import { required } from '@vuelidate/validators'

export default {
  setup() {
    const rules = {
      name: { required }
    }
    const v$ = useVuelidate(rules, currentUser)
    return { v$ }
  }
}

API 服务封装

创建 apiService.js

const API_URL = '/api/users'

export default {
  getAll() {
    return axios.get(API_URL)
  },
  create(user) {
    return axios.post(API_URL, user)
  },
  update(id, user) {
    return axios.put(`${API_URL}/${id}`, user)
  },
  delete(id) {
    return axios.delete(`${API_URL}/${id}`)
  }
}

注意事项

  1. 后端 API 需要实现对应的 RESTful 接口
  2. 处理网络请求错误时应该添加 catch 块
  3. 对于大型项目建议使用 Vuex/Pinia 集中管理状态
  4. 表单提交建议添加防抖或禁用按钮防止重复提交
  5. 列表数据量大时应考虑分页加载

以上方案可根据实际项目需求进行调整,核心逻辑是通过 Vue 的响应式特性同步前端状态与后端数据。

vue实现CRUD

标签: vueCRUD
分享给朋友:

相关文章

vue实现下载暂停

vue实现下载暂停

Vue实现下载暂停功能 在Vue中实现下载暂停功能,通常需要结合XMLHttpRequest或Fetch API的AbortController来控制请求中断。以下是具体实现方法: 使用XMLHtt…

vue实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 29…

代码实现vue

代码实现vue

创建Vue项目 使用Vue CLI快速初始化项目,确保已安装Node.js和npm/yarn: npm install -g @vue/cli vue create my-vue-project…

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…