Vue实现购物车
1、导入Vue要用的js没有的可以点击到官网下载
最好两个都下
2、新建div取名字<div id="app">
3、写入数据,实例化Vue
var messages = [{
sname: "城南旧事",
num: 1,
price: 48,
data: "2015-11-19",
imgae:"img/南城旧事.jpg",
dataSize:false,
},
{
sname: "飞机模型",
num: 1,
price: 28,
data: "2015-11-19",
imgae:"img/飞机模型.jpg",
dataSize:false,
}
]
const app = new Vue({
el: '#app',
4、定义一个表格,用来存储信息
<table>
<tr>
<th v-for="item in title">{{item}}</th>
</tr>
<tr v-for="(d,id) in message">
<td>{{id+1}}</td>
<td>{{d.sname}}</td>
<td><img v-bind:src="d.imgae" width="100px" :class="{imgae:d.dataSize}" @mouseover="over(id)" @mouseleave="leave(id)" /></td>
<td>{{d.data}}</td>
<td>
<button v-on:click="subtract(id)" v-if="d.num>0">-</button> {{d.num}}
<button v-on:click="plus(id)">+</button>
</td>
<td>¥{{decimals(id)}}</td>
<td><button @click="deleterow(id)">移除</button></td>
</tr>
</table>
5、将数据写入表格
<tr>
<th v-for="item in title">{{item}}</th>
</tr>
<tr v-for="(d,id) in message">
<td>{{id+1}}</td>
<td>{{d.sname}}</td>
<td><img v-bind:src="d.imgae" width="100px" :class="{imgae:d.dataSize}" @mouseover="over(id)" @mouseleave="leave(id)" /></td>
<td>{{d.data}}</td>
<td>
<button v-on:click="subtract(id)" v-if="d.num>0">-</button> {{d.num}}
<button v-on:click="plus(id)">+</button>
</td>
<td>¥{{decimals(id)}}</td>
<td><button @click="deleterow(id)">移除</button></td>
</tr>
<h1>总价格:{{littel}}</h1>
7、实现
computed: {
littel: function() {
let result = 0;
for(let i = 0; i < this.message.length; i++) {
result += this.message[i].price * this.message[i].num;
}
return result;
}
},
methods: {
plus: function(id) {
this.message[id].num++;
},
subtract: function(id) {
this.message[id].num--;
},
decimals: function(id) {
return this.message[id].price.toFixed(2);
},
deleterow: function(id) {
this.message.splice(id, 1);
},
over:function(id){
this.message[id].dataSize = true;
},
leave:function(id){
this.message[id].dataSize = false;
}
}
})