Html 代碼:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="./style.css" /> <script src="./vue.js"></script> <title>Shopping Cart</title> </head> <body> <div id="app"> <table> <tr> <th>序號</th> <th>商品名稱</th> <th>單價</th> <th>數量</th> <th>操作</th> </tr> <tr v-for="product in products"> <td>{{product.id}}</td> <td>{{product.name}}</td> <td>${{product.price}}</td> <td> <button v-bind:disabled="product.count===0" v-on:click="product.count-=1"> - </button> {{product.count}} <button v-on:click="product.count+=1"> + </button> </td> <td><button v-on:click="product.count=0">歸零</button></td> </tr> <tr> <td colspan="5" class="no">總價:${{totalPrice()}}</td> </tr> </table> </div> <script src="./main.js"></script> </body> </html>
CSS 代碼:
#app { position: relative; display: flex; justify-content: center; } table { position: absolute; width: 50%; border: 1px solid black; border-radius: 7px; top: 70px; } th { height: 50px; } td { height: 30px; text-align: center; border-bottom: 1px solid #ddd; } .no { text-align: right; padding-right: 20px; border-bottom: none; }
JavaScript 代碼:
var vm = new Vue({ el: '#app', data: { products: [ { id: 1, name: 'iPhone 11', price: 699, count: 1 }, { id: 2, name: 'iPhone 11 Pro', price: 999, count: 1 }, { id: 3, name: 'iPhone 11 Pro Max', price: 1099, count: 1 }, ], }, methods: { totalPrice: function () { var num = 0 for (var i = 0; i < this.products.length; i++) { num += this.products[i].count * this.products[i].price } return num }, }, })