Vue3初学之商品的增,删,改功能
用一个商品的后台管理进行增,删,改的实现。
案例进行学习:
<template>
<div>
<el-button type="primary" @click="handleNew">新增商品</el-button>
<el-table :data="goodsList" style="width: 100%">
<el-table-column prop="id" label="商品ID" />
<el-table-column prop="name" label="商品名称" />
<el-table-column prop="price" label="价格" />
<el-table-column prop="stock" label="库存" />
<el-table-column fixed="right" label="操作" width="180">
<template #default="{row}">
<el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
<el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 新增/编辑商品弹窗 -->
<el-dialog v-model="dialogVisible" :title="dialogTitle">
<el-form :model="form" label-width="100px">
<el-form-item label="商品名称">
<el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
</el-form-item>
<el-form-item label="价格">
<el-input-number v-model="form.price" placeholder="请输入价格" :min="0"></el-input-number>
</el-form-item>
<el-form-item label="库存">
<el-input-number v-model="form.stock" placeholder="请输入库存" :min="0"></el-input-number>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit">确定</el-button>
</span>
</el-dialog>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';
const goodsList = ref([
{ id: 1, name: '商品1', price: 100, stock: 50 },
{ id: 2, name: '商品2', price: 200, stock: 30 }
]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({ name: '', price: 0, stock: 0 });
// 新增商品
const handleNew = () => {
dialogTitle.value = '新增商品';
form.value = { name: '', price: 0, stock: 0 };
dialogVisible.value = true;
};
// 编辑商品
const handleEdit = (row) => {
dialogTitle.value = '编辑商品';
form.value = { ...row };
dialogVisible.value = true;
};
// 删除商品
const handleDelete = (row) => {
ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
const index = goodsList.value.findIndex(item => item.id === row.id);
goodsList.value.splice(index, 1);
});
};
// 提交表单
const handleSubmit = () => {
if (dialogTitle.value === '新增商品') {
const newId = goodsList.value.length + 1;
goodsList.value.push({ ...form.value, id: newId });
} else {
const index = goodsList.value.findIndex(item => item.id === form.value.id);
goodsList.value[index] = { ...form.value };
}
dialogVisible.value = false;
};
</script>
效果: