用vue写一个商品管理页面 1.id 2.商品名称 3.单价price 4.数量num 1.展示数据 2. 增加 3. 修改 回显 4. 删除 提示! 让用户点确认操作
时间: 2024-02-01 07:02:18 浏览: 98
以下是一个简单的商品管理页面的Vue代码:
```html
<template>
<div>
<h2>商品管理</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in goods" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>{{ item.num }}</td>
<td>
<button @click="editGoods(index)">修改</button>
<button @click="deleteGoods(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<hr>
<h3 v-if="isEditing">修改商品</h3>
<form @submit.prevent="submitForm">
<div>
<label for="id">ID:</label>
<input type="text" id="id" v-model="currentGoods.id" :readonly="isEditing">
</div>
<div>
<label for="name">商品名称:</label>
<input type="text" id="name" v-model="currentGoods.name">
</div>
<div>
<label for="price">单价:</label>
<input type="number" id="price" v-model="currentGoods.price">
</div>
<div>
<label for="num">数量:</label>
<input type="number" id="num" v-model="currentGoods.num">
</div>
<div>
<button type="submit">{{ isEditing ? '更新' : '添加' }}</button>
<button type="button" v-if="isEditing" @click="cancelEdit">取消</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
goods: [
{
id: 1,
name: '商品1',
price: 10,
num: 100,
},
{
id: 2,
name: '商品2',
price: 20,
num: 200,
},
{
id: 3,
name: '商品3',
price: 30,
num: 300,
},
],
currentGoods: {
id: '',
name: '',
price: '',
num: '',
},
isEditing: false,
};
},
methods: {
editGoods(index) {
this.currentGoods = { ...this.goods[index] };
this.isEditing = true;
},
deleteGoods(index) {
if (confirm('确定要删除该商品吗?')) {
this.goods.splice(index, 1);
}
},
submitForm() {
if (this.isEditing) {
const index = this.goods.findIndex(item => item.id === this.currentGoods.id);
this.goods.splice(index, 1, this.currentGoods);
} else {
this.currentGoods.id = this.goods[this.goods.length - 1].id + 1;
this.goods.push({ ...this.currentGoods });
}
this.currentGoods = {
id: '',
name: '',
price: '',
num: '',
};
this.isEditing = false;
},
cancelEdit() {
this.currentGoods = {
id: '',
name: '',
price: '',
num: '',
};
this.isEditing = false;
},
},
};
</script>
```
这个页面包括了展示数据、增加、修改和删除操作。其中,展示数据用`v-for`指令遍历`goods`数组,增加操作通过`submitForm`方法实现,修改操作通过`editGoods`方法实现,删除操作通过`deleteGoods`方法实现。在修改和删除操作中,都使用了`confirm`方法弹出提示框,让用户确认操作。
阅读全文