Vue实现简易购物车

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="gbk">
 5 <title>Vue 测试实例</title>
 6 <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
 7 </head>
 8 <body>
 9 <div id="app">
10     <div v-for='(item, index) in books'>
11         <p>
12             <span>
13                 书编号:{{item.id}}, 书名:{{item.name}}, 价格:{{item.price}}
14             </span>
15         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
16         <button @click="add(index)">+</button>
17         &nbsp;{{item.number}}&nbsp;
18         <button @click="reduce(index)">-</button>
19         </p>
20     </div>
21     <hr/>
22     总和:&nbsp;&nbsp;<font color="red"><b>{{sum}}</b></font>&nbsp;元
23 </div>
24 
25 <script>
26 new Vue({
27   el: '#app',
28   data: {
29     books: [
30         {id:10,name:'山楂树之恋',price:100,number:0},
31         {id:20,name:'七月与安生',price:100,number:0},
32         {id:30,name:'解忧杂货铺',price:499,number:0},
33         {id:40,name:'富婆通讯录',price:999,number:0}
34     ]
35   },
36   methods:{
37       add(index){
38         if(this.books[index].number === 5){
39             alert('亲,您真土豪,本书限购5本哦!')
40             return
41         }
42         this.books[index].number++
43     },
44     reduce(index){
45         if(this.books[index].number === 0){
46             return
47         }
48         this.books[index].number--
49     }
50   },
51   computed:{
52       sum:function(){
53         let sumprice = 0
54         for(let i = 0; i < this.books.length; i++){
55             sumprice += this.books[i].number * this.books[i].price
56         }
57         return sumprice
58     }
59   }
60 })
61 </script>
62 </body>
63 </html>

页面:

猜你喜欢

转载自www.cnblogs.com/wldbky/p/12957527.html