
結果如圖:
代碼html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app" > <div v-if="books.length>0"> <table> <thead> <tr> <th>書籍名稱</th> <th>出版日期</th> <th>價格</th> <th>數量</th> <th>購買數</th> <th>操作</th> <th>移除</th> </tr> </thead> <tbody> <tr v-for="(item,index) in books"> <th >{{item.id}}</th> <th >{{item.name}}</th> <th >{{item.data}}</th> <th >{{item.price|showY}}</th> <!-- 價格這里添加了過濾器--> <th ><button @click="insc(index)">+</button> {{item.count}} <button @click="dec(index)" v-bind:disabled="item.count<=1">-</button> </th> <th><button @click="removeit(index)">移除</button></th> </tr> </tbody> </table> <h3>總價格 :{{totalPrice}}</h3> </div> <div v-else> 購物車為空 </div> </div> </body> <!--再之前和之后引入有區別--> <script src="../JS/vue.js"></script> <script src="../JS/main.js"></script> </html>
main.js
const app=new Vue({ el:"#app", //掛載那個元素//注意這里有井號 初學者容易掉 data:{ books:[{ id :1, name:"算法", data:"2006-9", price: 85, count:1}, { id :2, name:"unix編程", data:"2006-9", price: 85, count:1}, { id :3, name:"java入土", data:"2006-9", price: 85, count:1}, ] }, methods:{ insc(index){ this.books[index].count++;//注意這里的寫法 }, dec(index) { this.books[index].count--;//注意這里的寫法 }, removeit(index) { this.books.splice(index,1)//刪除自身 } }, filters:{//注意是filtes 夾着s showY(price) { return "Y" +price } },computed: { totalPrice() //直接調用不用加括號 { let totleprice=0; for (let i=0;i<this.books.length;i++) {totleprice+=this.books[i].price*this.books[i].count; } return totleprice } }, })
