Vue购物车案例和for...in与for...of的区别
html代码
<div id="app">
<div v-if="book.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in book">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decreament(index)" :disabled="item.count <= 1">-</button> {{item.count}}
<button @click="increament(index)">+</button>
</td>
<td><button @click="removeHandle">删除</button></td>
</tr>
</tbody>
</table>
<h2 style="margin: 0 auto;width: 200px;">总价:{{totalPrice|showPrice}}</h2>
</div>
<h2 v-else>空</h2>
</div>
js代码
const app = new Vue({
el: "#app",
data: {
book: [
{ id: 1, name: "围城", date: "2020.01.25", price: 88.00, count: 1, },
{ id: 2, name: "狂人日记", date: "2020.07.25", price: 58.00, count: 1, },
{ id: 3, name: "朝花夕拾", date: "2020.11.05", price: 85.00, count: 1, },
{ id: 4, name: "呐喊", date: "2020.05.05", price: 48.00, count: 1, }
],
},
computed: {
totalPrice() {
// 1.普通for循环
// let totalPrice = 0;
// for (let i = 0; i < this.book.length; i++) {
// totalPrice += this.book[i].price * this.book[i].count
// }
// return totalPrice;
// }
// 2.for...in
// 如果是对象的话得到的i是表示obj对象的每一个键值对的键
//需要使用obj[i]来取到每一个值
//数组的话输出就是索引但是是字符串的形式'0','1','2'
// let totalPrice = 0
// for (let i in this.book) {
// const book = this.book[i]
// totalPrice += book.price * book.count
// }
// return totalPrice;
// 3.for...of
//for…of循环读取键值
let totalPrice = 0
for (let item of this.book) {
totalPrice += item.price * item.count
}
return totalPrice
}
},
methods: {
increament(index) {
this.book[index].count++
},
decreament(index) {
// if (this.book[index].count > 1) {
this.book[index].count--
}//
},
removeHandle(index) {
this.book.splice(index, 1)
},
},
filters: {
showPrice(price) {
return "¥" + price.toFixed(2)
}//设置价钱的标准格式
}
})
<style>table{margin:0 auto}th{padding:14px 24px;background-color:#ccc}td{text-align:center}td button{margin:0 5px}</style>

浙公网安备 33010602011771号