我做的购物车不太美观,有兴趣的话可以引入好看的一些样式
我所实现的功能有遍历水果,数量加减的修改,各个商品小计,所有商品总计,还有商品的添加与删除
我的代码如下:
html代码:
<div id="app">
<div style="text-align: center;">
<button style="text-align: center;" @click="add">添加</button>
<table style="width: 80%;" id="mytable">
<tr>
<td>商品编号</td>
<td>商品名称</td>
<td>商品价格</td>
<td>商品数量</td>
<td>商品小计</td>
<td>操作</td>
</tr>
<tr v-for="(v,index) in shops">
<td>{{v.id}}</td>
<td>{{v.name}}</td>
<td><input v-model="v.price" style="text-align: center;" />
</td>
<td>
<button @click="v.num+=1">+</button><input v-model="v.num" style="width: 30px;text-align: center;" /><button
:disabled="v.num==0" @click="v.num-=1">-</button>
</td>
<td>{{v.price*v.num}}</td>
<td>
<button @click="del(index)">删除</button>
</td>
</tr>
</table><br>
<h3><span style="color: blue;">总计:{{total}}</span></h3>
</div>
</div>
js代码:
<script type="text/javascript">
let app = new Vue({
el: '#app',
data() {
return {
shops: [{
id: 1,
name: '苹果',
price: 3,
num: 1
}, {
id: 2,
name: '香蕉',
price: 4.5,
num: 1
}, {
id: 3,
name: '雪梨',
price: 10,
num: 1
}, {
id: 4,
name: '红柚',
price: 4.5,
num: 1
}, {
id: 5,
name: '红提',
price: 5,
num: 1
}, {
id: 6,
name: '西瓜',
price: 0.8,
num: 1
}]
}
},
computed: {
total() {
let total = 0;
for (let index = 0; index < this.shops.length; index++) {
total += this.shops[index].price * this.shops[index].num;
}
return total;
}
},
methods: {
add() {
let sid = prompt('请输入商品编号!');
let sname = prompt('请输入商品名称!');
let sprice = prompt('请输入商品价格!');
let snum = prompt('请输入商品数量!');
app.shops.push({
id: parseInt(sid),
name: sname,
price: parseFloat(sprice),
num: parseInt(snum)
})
},
del(v) {
this.shops.splice(v, 1);
}
}
})
</script>