<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="vue.min.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
</head>
<body>
<div id="app">
<table class="table table-bordered" id="productListTable" >
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products ">
<td>{{product.name}}</td>
<td>¥{{product.names}}</td>
<td>
<a href="#nowhere" @click="edit(product)">编辑</a>
<a href="#nowhere" @click="deleteproduct(product.id)">删除</a>
</td>
</tr>
<tr>
<td>
商品名称:
<input type="text" class="form-control" v-model="productAdd.name" />
<br>
单价:
<input type="number" class="form-control" v-model="productAdd.names" />
<br>
<button type="button" class="btn btn-default" v-on:click="add">增加</button>
</td>
</tr>
</tbody>
</table>
<div id="Update">
<table class="table table-bordered">
<tr>
<td>
商品名称:
<input type="text" class="form-control" v-model="productUpdate.name" />
</td>
</tr>
<tr>
<td>
单价:
<input type="number" class="form-control" v-model="productUpdate.names" />
</td>
</tr>
<tr>
<td>
<input type="hidden" v-model="productUpdate.id" />
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-default" v-on:click="update">修改</button>
<button type="button" class="btn btn-default" v-on:click="cancel">取消</button>
</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
//修改区域隐藏起来先
$("#Update").hide();
//Model
var data = {
products: [
{ id: 1, name: '红米4A',names: 799},
{ id: 2, name: '红米5A', names: 899},
{ id: 3, name: '红米6A', names: 999},
{ id: 4, name: '红米20k', names: 2399},
{ id: 5, name: '小米9', names: 3299},
],
productAdd: { id: 0, name: '', names: '0'},
productUpdate: { id: 0, name: '', names: '0'}
};
//用于记录最大id值
var maxId = 5;
//计算最大值
for (var i=0;i<data.products.length;i++){
if (data.products[i].id > maxId)
maxId= this.products[i].id;
}
//ViewModel
var vue = new Vue({
el: '#app',
data: data,
methods: {
add: function (event) {
//获取最大id
maxId++;
//赋予新id
this.productAdd.id = maxId;
if(this.productAdd.name.length==0)
this.productAdd.name = "Product"+this.productAdd.id;
//把对象加入到数组
this.products.push(this.productAdd);
//让 productAdd 指向新的对象
this.productAdd = { id: 0, name: '', names: '0'}
},
deleteproduct: function (id) {
console.log("id"+id);
for (var i=0;i<this.products.length;i++){
if (this.products[i].id == id) {
this.products.splice(i, 1);
break;
}
}
},
edit: function (product) {
$("#productListTable").hide();
$("#Update").show();
this.productUpdate = product;
},
update:function(){
//因为v-model,已经同步修改了,所以只需要进行恢复显示就行了
$("#productListTable").show();
$("#Update").hide();
},
cancel:function(){
//其实就是恢复显示
$("#productListTable").show();
$("#Update").hide();
}
}
});
</script>
</body>
</html>
Vue实现简单的购物车
最新推荐文章于 2022-09-01 10:52:23 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)