vue 写购物车
用到了 计算属性(computed)、双向绑定(v-model)的复选框单用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,i) of cards" :key="i">
<input type="checkbox" v-model="item.is_checked">
{{item.pid}} | {{item.pname}} | {{item.price}} | {{item.count}} 小计:¥{{(item.price*item.count).toFixed(2)}}
<button @click="del" :data-i="i">×</button>
</li>
<h1>总计:{{total.toFixed(2)}}</h1>
</ul>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
cards: [
{ pid: 1, pname: "小米", price: 1000, count: 3, is_checked: false },
{ pid: 1, pname: "苹果", price: 4000, count: 4, is_checked: false },
{ pid: 1, pname: "华为", price: 2000, count: 2, is_checked: false },
],
},
methods: {
del(e) {
var i = parseInt(e.target.dataset.i);
this.cards.splice(i, 1);
}
},
computed: {
total() {
/* var total=0;
for(var c of this.cards){
if(c.is_checked){
total+=c.price*c.count
}
}
return total; */
return this.cards.filter(
item => item.is_checked
).reduce(
(prev, item) => prev + item.price * item.count, 0
)
}
}
})
</script>
</body>
</html>