Vue購物車案例和for...in與for...of的區別
阿新 • • 發佈:2021-06-19
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>