vue原生实现crud功能
Vue 原生实现 CRUD 功能
在 Vue 中实现 CRUD(Create, Read, Update, Delete)功能,可以通过组合式 API 或选项式 API 完成。以下是基于组合式 API 的实现方案,包含核心代码和逻辑。
数据准备与状态管理
使用 ref 或 reactive 管理数据状态,模拟一个简单的待办事项列表:
import { ref } from 'vue';
const items = ref([]);
const newItem = ref('');
const editingIndex = ref(-1);
创建(Create)
添加新条目到列表:
const addItem = () => {
if (newItem.value.trim()) {
items.value.push({ id: Date.now(), text: newItem.value });
newItem.value = '';
}
};
读取(Read)
渲染列表数据:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.text }}
<button @click="editItem(index)">Edit</button>
<button @click="deleteItem(index)">Delete</button>
</li>
</ul>
</template>
更新(Update)
编辑现有条目:
const editItem = (index) => {
editingIndex.value = index;
newItem.value = items.value[index].text;
};
const updateItem = () => {
if (editingIndex.value !== -1 && newItem.value.trim()) {
items.value[editingIndex.value].text = newItem.value;
editingIndex.value = -1;
newItem.value = '';
}
};
删除(Delete)
移除指定条目:
const deleteItem = (index) => {
items.value.splice(index, 1);
};
表单绑定与操作整合
将方法与表单绑定:
<template>
<input v-model="newItem" placeholder="Enter item">
<button
@click="editingIndex === -1 ? addItem() : updateItem()"
>
{{ editingIndex === -1 ? 'Add' : 'Update' }}
</button>
</template>
完整示例代码
整合后的组件代码:
<template>
<div>
<input v-model="newItem" placeholder="Enter item">
<button @click="editingIndex === -1 ? addItem() : updateItem()">
{{ editingIndex === -1 ? 'Add' : 'Update' }}
</button>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.text }}
<button @click="editItem(index)">Edit</button>
<button @click="deleteItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([]);
const newItem = ref('');
const editingIndex = ref(-1);
const addItem = () => {
if (newItem.value.trim()) {
items.value.push({ id: Date.now(), text: newItem.value });
newItem.value = '';
}
};
const editItem = (index) => {
editingIndex.value = index;
newItem.value = items.value[index].text;
};
const updateItem = () => {
if (editingIndex.value !== -1 && newItem.value.trim()) {
items.value[editingIndex.value].text = newItem.value;
editingIndex.value = -1;
newItem.value = '';
}
};
const deleteItem = (index) => {
items.value.splice(index, 1);
};
</script>
关键点说明
- 响应式数据:使用
ref或reactive确保数据变化触发视图更新。 - 条件渲染:通过
editingIndex切换添加/更新模式。 - 列表操作:数组方法
push和splice直接修改响应式数据。
此实现无需额外库,适合小型应用。如需复杂状态管理,可结合 Pinia 或 Vuex。







