当前位置:首页 > VUE

vue前端实现增删改

2026-02-23 15:15:23VUE

使用 Vue 实现增删改功能

数据绑定与列表渲染

通过 v-model 实现表单数据双向绑定,结合 v-for 渲染列表。示例代码:

<template>
  <div>
    <input v-model="newItem.name" placeholder="名称">
    <button @click="addItem">添加</button>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.name }}
        <button @click="editItem(index)">编辑</button>
        <button @click="deleteItem(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

添加功能实现

初始化数据并定义添加方法:

vue前端实现增删改

<script>
export default {
  data() {
    return {
      items: [],
      newItem: { name: '' }
    }
  },
  methods: {
    addItem() {
      if (this.newItem.name.trim()) {
        this.items.push({...this.newItem});
        this.newItem.name = '';
      }
    }
  }
}
</script>

删除功能实现

通过数组的 splice 方法删除指定索引项:

vue前端实现增删改

methods: {
  deleteItem(index) {
    this.items.splice(index, 1);
  }
}

编辑功能实现

添加编辑状态和更新方法:

<template>
  <div v-if="editingIndex === null">
    <input v-model="newItem.name">
    <button @click="addItem">添加</button>
  </div>
  <div v-else>
    <input v-model="editItemData.name">
    <button @click="updateItem">更新</button>
  </div>
</template>

<script>
methods: {
  editItem(index) {
    this.editingIndex = index;
    this.editItemData = {...this.items[index]};
  },
  updateItem() {
    this.items.splice(this.editingIndex, 1, {...this.editItemData});
    this.cancelEdit();
  },
  cancelEdit() {
    this.editingIndex = null;
    this.editItemData = { name: '' };
  }
}
</script>

状态管理(可选)

对于复杂场景可使用 Vuex:

// store.js
const store = new Vuex.Store({
  state: {
    items: []
  },
  mutations: {
    ADD_ITEM(state, item) {
      state.items.push(item);
    },
    DELETE_ITEM(state, index) {
      state.items.splice(index, 1);
    }
  }
});

注意事项

  1. 始终为 v-for 设置唯一的 :key
  2. 复杂表单建议使用 Vue.set 确保响应式更新
  3. 大量数据操作时考虑使用计算属性优化性能

标签: vue
分享给朋友:

相关文章

vue实现多人视频

vue实现多人视频

实现多人视频通话的Vue方案 使用WebRTC技术结合Vue框架可以构建多人视频通话应用。以下是核心实现方法: 技术栈选择 Vue 2/3作为前端框架 WebRTC用于实时通信 Socket.io…

vue请求实现进度条

vue请求实现进度条

实现请求进度条的方法 在Vue中实现请求进度条可以通过多种方式完成,常见的有使用第三方库如axios结合nprogress或自定义进度条组件。以下是几种实现方法: 使用axios和nprogress…

vue实现边框

vue实现边框

Vue 实现边框的方法 在 Vue 中实现边框效果可以通过多种方式完成,包括内联样式、CSS 类绑定、动态样式以及使用第三方 UI 库。以下是几种常见的实现方法。 内联样式绑定 使用 Vue 的 :…

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转…

vue实现api

vue实现api

Vue 实现 API 调用 在 Vue 中调用 API 通常涉及使用 axios 或 fetch 发送 HTTP 请求,并结合 Vue 的响应式特性管理数据。以下是常见的实现方式: 安装 axi…

vue实现增加

vue实现增加

实现 Vue 中的新增功能 在 Vue 中实现新增功能通常涉及数据绑定、表单处理和状态管理。以下是几种常见的实现方式: 数据绑定与列表渲染 通过 v-model 绑定表单输入,使用数组的 pu…