vue3 实现增删改查
时间: 2023-11-15 15:00:03 浏览: 121
Vue3可以通过组合API和Composition API来实现增删改查功能。下面是一个简单的例子:
1. 首先在组件中定义数据和方法:
```
<template>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="edit(index)">编辑</button>
<button @click="del(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<form @submit.prevent="submit">
<input type="text" v-model="formData.name" placeholder="姓名">
<input type="text" v-model="formData.age" placeholder="年龄">
<button type="submit">提交</button>
</form>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const list = reactive([
{ name: '张三', age: 18 },
{ name: '李四', age: 20 },
{ name: '王五', age: 22 }
])
const formData = reactive({
name: '',
age: ''
})
const editIndex = reactive(-1)
const submit = () => {
if (editIndex.value === -1) {
list.push(formData)
} else {
list[editIndex.value] = formData
editIndex.value = -1
}
formData.name = ''
formData.age = ''
}
const edit = (index) => {
formData.name = list[index].name
formData.age = list[index].age
editIndex.value = index
}
const del = (index) => {
list.splice(index, 1)
}
return {
list,
formData,
submit,
edit,
del
}
}
}
```
2. 在模板中使用数据和方法:
```
<template>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="edit(index)">编辑</button>
<button @click="del(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<form @submit.prevent="submit">
<input type="text" v-model="formData.name" placeholder="姓名">
<input type="text" v-model="formData.age" placeholder="年龄">
<button type="submit">提交</button>
</form>
</div>
</template>
```
3. 最后,你可以在组件中使用这些方法和数据来实现增删改查功能。